﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;        
using System.Collections;
using UFIDA.U8.DB.Model;
using UFIDA.U8.DB;
using UFIDA.U8.PUB;
using System.Threading; 

using log4net;
using System.IO;
using Newtonsoft.Json;
using Nbcb.Cobp.SDK;
using System.Diagnostics;
using System.Net;
using UFIDA.U8C.AnLianDB;
using UFIDA.U8C.AnLianDB.Model;
using Newtonsoft.Json.Linq; 

namespace UFIDA.U8C.AnLian.NBBankSync
{
    
    public partial class SyncUI :  Form
    {
        #region init
        private static ILog log = LogManager.GetLogger("Program");
        private static System.Timers.Timer aTimer = new System.Timers.Timer(); 
        private static int inTimer = 0;
        BaseSetUI frmBasSet;

        private string _connectstring = Common.getConfigInfo("ConnectString");
        private string privateKey = Common.getConfigInfo("privateKey"); //"MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCbaLzsHtojdwK4X3yO3A99HWiv1JmEwe+w9ovs5O9JjCgVmDQQOkADVayWaCVwLwpGnvsgcA4AUd49Yz8RxqWRa5RP+x6X9/fdDzidpAI/ljaIQDTclB8L1PnAgefFQr5SwRjPelvbS20sBJ4zBz5JftRnDtjvs0JkkM+Z0Wp3h6QjdXGX/yLld7UV2CWW/AReH2ix6LtCveewFPODHasxe8GgUo2urtdpGz6i5GbeGAEeF9jed1mIKMBSBKATXH5qC/Gx+NRKJL0IJwuaLb64IwQOF16nNbK/Zq20thDhCZqMef4cuFCx2TzAdJIydt+IgfQU8RZ57jltROlbJYpNAgMBAAECggEAFueR6I8HgXCZ4wiXuApw8fSyqC+CTNG0fPVpXAnFxqY0hjI/giDDrHolDKne0rDsJ8poorhBKATo501IT1tirZMYcc1GDgnK6zbCFmHEvxBpix1DbTsbdEf4Y0oCGc2jdVjmSjXzcdelCHbJxiWMJZLexS2oBXP7Fg1Nu5LkySbmpgYC253/EtcSOue8ldNNSGBinS2MZ9A04312ebBF2+oK5dBejBV0P7El9HfHU8Edknn+QnmXnDr3SFhZMIfstfB3/n+ot4m4ITb2rWU6+6Pj6Mi0ZgNSpjZfGAF2DRDysSM/KKfq14SVCD/mUM8SNgi3BwKhkxjyhcEAPdvmIQKBgQDZA+7Sk5tsYYfMpNncyjfnCILYk1xqGGMkAyL2y4d4L+c+Q32TrnglEvs2wytgpO4o1IlGQ6UKUsDUMlCRoqUnzzo4S1ZrVUQksjzAirH+r0NOhuWJkcSTFUXhJao2H1D8JLoRkWfQA9TQ4FK3WpysL+09ULDbdjBRuZ/4C+3t9QKBgQC3U6r2AyyX4Z/JAi6Prr2DJNp53iO+gqzoT9QDJ06LhhoEhPOa+Qf2LqaFMacqi7zMt0tJXMe0pK4XPLwZcUvVIy0p/WWoWS68rI235uiXVAq8ljS+MSVOKh1EFLCuFXkfQ63/5QBQxqDHc1YGm8+gAjvKyMP953LNrtVP57db+QKBgByUhwRWijaI1bCe2U5Zl2km1sydA6O5WH0qqJUmEs5CSMsLamNjq9D+IfWBWJoevnrEGtwVFow4f8qyYaf8apHGmd1GFriF/zZx/sxAt9ZZ0Jxr6ZjniKLyP0S6iCMelrTORW8A3lIn3wQvNtWM6mtG2JClqtUMSKrKroWlVI1tAoGBALZTTPVNJN2M9Jg6Rkp6FFrInUyU5GHFnueQ9R+JyTE0Vs3l2E1pnUR3Ev/m6QWEYmoLZaH511hObCIKMlzvc+bvDCz1qlPrFnNo/a1Hxk0ytVbn4F7DjAGYGvEpzqnkC0lPy05z14N+eErE52q9LZpKfmLolxv/QwtS9S16G78pAoGAKLKF1ArA1i6yQetCixPxmSS8XGHKWY0CqMROTOXmXOXru4i9w3ua+gzbwkDwlh2PUXDXJNylUhBxyUAlb2CQ6pXczONx/UvSLoda70jKgik+oSqbPR8U6jXycf8sspOFTlOHgH7IplIyssaw4ccZ0Qq15Gzku4bgjzgZ3kbabTg=";
        private string accid;
        private string url = "";
        private string tragetconnectstring = ""; //帐套数据库连接字
        
        private string path = Path.GetFullPath("../..");//获取项目根目录
        private string configName = "/config.ini";

        //u8c配置
        private static string u8curl = common.getConfigInfo("u8curl");
        private static string projecturl = u8curl + "/u8cloud/api/uapbd/bdjobbasfil/save";
        private static string customerurl = u8curl + "/u8cloud/api/uapbd/custdoc/insert";
        


        //文件下载默认路径
        private string sPath = @"d:\NBBankFile";

        //凭证制单人
        private string _cbill { get; set; }


        /// <summary>
        /// 客户号
        /// </summary>
        private string custID { get; set; }
        /// <summary>
        /// 账号
        /// </summary>
        private string accountcode { get; set; }

        public SyncUI( )
        {
            // TODO: Complete member initialization
            InitializeComponent();
            try
            {
                log.Debug("asdaefae");

                NbcbSDK.init(path, configName, privateKey);
                this.getaccount();
            }
            catch (Exception e)
            {
                MessageBox.Show("初始化失败,检查银行配置文件" + e.Message);
            } 
        }

        #endregion
        
        #region 目标账套
        private void getaccount()
        {
            string sql = "select * from cust_syncacount where flag = 1 ";
            dsacc = DbHelperSQL.Query(sql, "cust_syncacount", _connectstring);

            if (dsacc.Tables[0] != null && dsacc.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < dsacc.Tables[0].Rows.Count; i++)
                {
                    edtacc.Items.Add(dsacc.Tables[0].Rows[i]["accname"].ToString());
                }
            }
        }

        private void edtacc_SelectedIndexChanged(object sender, EventArgs e)
        {
            string accname = edtacc.Text;
            if (string.IsNullOrEmpty(accname))
            {
                tragetconnectstring = "";
                return;
            }
            try
            {
                DataView dv = dsacc.Tables[0].DefaultView;
                dv.RowFilter = "accname = '" + accname + "'";
                if (dv.Count > 0)
                {
                    string cserver = dv[0]["cserver"].ToString();
                    string cuser = dv[0]["cuser"].ToString();
                    string psd = dv[0]["psd"].ToString();
                    string dbname = dv[0]["dbname"].ToString();

                    custID = dv[0]["custid"].ToString();
                    tragetconnectstring = this.gettragetconnect(cserver, cuser, psd, dbname);
                    accid = dv[0]["accname"].ToString();
                    
                    LogHelper.WriteLine("目标数据库：" + tragetconnectstring);
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLine("error：" + ex);
                MessageBox.Show(ex.Message);
            }
            
        }

        private string gettragetconnect(string cserver, string cuser, string psd, string dbname)
        {
            string constr = "Server = " + cserver + ";User = " + cuser + "; Pwd = " + psd + ";Database = " + dbname;
            using (SqlConnection sql = new SqlConnection(constr))
            {
                try
                {
                    sql.Open();
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
            return constr;
        }
        #endregion
                
        #region 日志
        private delegate void txtInvokeCallback(string msg);
        private void m_comm_MessageEvent(string msg)
        {
            if (txtLog.InvokeRequired)
            {
                txtInvokeCallback msgCallback = new txtInvokeCallback(m_comm_MessageEvent);
                txtLog.Invoke(msgCallback, new object[] { msg });
            }
            else
            {
                if (string.IsNullOrEmpty(msg))
                {
                    txtLog.Clear();
                }
                txtLog.AppendText(msg);
            }
        }
      

        #endregion
        
        #region 手工同步

        /// <summary>
        /// 停止同步
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStop_Click(object sender, EventArgs e)
        {
            setButtonState(true);
            aTimer.Stop();
            aTimer.Enabled = false;
        }

        /// <summary>
        /// 同即同步
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonX6_Click(object sender, EventArgs e)
        {
            try
            {
                syncByTime();
            }
            catch (Exception ex)
            {
                U8.PUB.LogHelper.WriteLine("数据同步出错：" + ex.Message);
            }
        }

        #endregion

        #region 定时同步

        /// <summary>
        /// 开始同步
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                dtCurDate.Text = "";
                setButtonState(false);
                aTimer.Interval = Convert.ToInt32(txtTime.Text) * 60000;
                aTimer.Enabled = true;
                aTimer.AutoReset = true;
                aTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);
            }
            catch (Exception ex)
            {
                m_comm_MessageEvent("数据同步出错：" + ex.Message);
                U8.PUB.LogHelper.WriteLine("数据同步出错：" + ex.Message);
            }
        }

        /// <summary>
        /// 帐套设置窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBasSet_Click(object sender, EventArgs e)
        {

            if (frmBasSet == null)
            {
                frmBasSet = new BaseSetUI();
            }
            frmBasSet.ShowDialog();
        }

        /// <summary>
        /// 设置按钮状态
        /// </summary>
        /// <param name="enable"></param>
        private void setButtonState(bool enable)
        {
            btnStop.Enabled = !enable;
            btnStart.Enabled = enable;
            txtTime.Enabled = enable;
        }
       
        private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs e)
        {
            //清理内存
            GC.Collect();
            GC.WaitForPendingFinalizers();
             
            //inTimer设置一个标志，表示一个Timer处理正在执行，下一个Timer发生的时候发现上一个没有执行完就放弃
            if (Interlocked.Exchange(ref inTimer, 1) == 0)
            {
                m_comm_MessageEvent("");
                this.syncByTime();
                Interlocked.Exchange(ref inTimer, 0);
            }

        }

        /// <summary>
        /// 根据时间戳同步交易明细记录及下载回单文件
        /// </summary>
        /// <param name="tragetconnectstring"></param>
        private void syncByTime()
        {
            string accname = string.Empty;
            string cserver = "", cuser = "", psd = "", dbname = "";
            
            try
            {

                txtLog.Clear();
                
                #region 银行流水
                
                //获取同步账套
                DataTable dt = this.getaccountInfo();
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        #region 帐套信息获取
                        accname = dr["accname"].ObjToString();
                        cserver = dr["cserver"].ToString();
                        cuser = dr["cuser"].ToString();
                        psd = dr["psd"].ToString();
                        dbname = dr["dbname"].ToString();
                        _cbill = dr["cbill"].ToString();

                    
                        tragetconnectstring = this.gettragetconnect(cserver, cuser, psd, dbname);
                        accid = dr["accname"].ToString();
                        custID = dr["custid"].ToString();
                        
                        #endregion

                        #region 交易明细
                        this.PostAccDetail(accid, tragetconnectstring); 
                        #endregion  

                        #region 获取下载文件
                        this.PostQueryReceipt(accid, tragetconnectstring); 
                        #endregion

                        #region 生成凭证 作废
                        //this.GLAdd(accid, tragetconnectstring);
                        #endregion

                    }
                }
              
                 
                #endregion


                #region 海象
                if (cbHx.Checked)
                {
                    this.syncHx();
                }
                #endregion  
            }
            catch (Exception e)
            {
                m_comm_MessageEvent(DateTime.Now + ":Error :" + e.Message + "\n");
                log.Error(e.StackTrace);
            }
        }

        private void syncHx() 
        { 
            //同步基础数据
            //同步项目档案  
            this.syncProject();
            //同步客户档案
            this.syncCustomer();
            //同步供应商档案
            this.syncSupplier();
        }

        #region 同步供应商
        /// <summary>
        /// 同步海象供应商到U8C
        /// </summary>
        private void syncSupplier()
        {
            m_comm_MessageEvent("开始同步海象供应商档案数据\n");
            string sql = "select hxid from wazh_supplier where iflag = 0 ";
            string js = "";
            string errMsg = "";
            string resResult = "";
            DataTable dt = UFIDA.MYSQL.DB.DbHelperSQL.QueryAsDT(sql, common.mysqlconn());
            if (dt == null || dt.Rows.Count == 0)
            {
                U8.PUB.LogHelper.WriteLine("没有供应商数据\n");
                m_comm_MessageEvent("没有供应商数据\n");
                return;
            }

            foreach (DataRow dr in dt.Rows)
            {
                string code = dr["hxid"].ToString();
                m_comm_MessageEvent("海象供应商档案" + code + "数据\n");
                js = this.getSupplierJs(code, common.mysqlconn());
                if (js.Equals(""))
                {
                    continue;
                }
                bool bpost = common.PostU8C(code, js, customerurl, ref resResult, ref errMsg);
                if (bpost)
                {
                    this.UpdCustomerFlag(code, 1, "", common.mysqlconn());
                }
                else
                {
                    this.UpdCustomerFlag(code, 0, errMsg, common.mysqlconn());
                }
            }
            m_comm_MessageEvent("同步海象供应商档案数据完成\n");
        }


        private void UpdSupplierFlag(string code, int iflag, string errMsg, string conn)
        {
            string sql = "update wazh_supplier set iflag = " + iflag + " , msg ='" + errMsg + "' where supplier = '" + code + "'";

            int icount = MYSQL.DB.DbHelperSQL.ExecuteSql(sql, conn);

        }

        private string getSupplierJs(string code, string u8conn)
        {
            string sql = "select * from vw_u8c_supplier where hxid = '" + code + "'";
 
            DataTable dt = MYSQL.DB.DbHelperSQL.QueryAsDT(sql, u8conn);
            if (dt != null && dt.Rows.Count > 0)
            {
                JObject cbdocvo = new JObject();
                JArray custList = new JArray();
                string jsonb = JsonConvert.SerializeObject(dt);
                JArray items = JArray.Parse(jsonb);
                JObject parentvo = new JObject();

                parentvo["parentvo"] = items[0];
                custList.Add(parentvo);
                parentvo["banks"] = this.getsupbanks(code, u8conn);
                cbdocvo["cbdocvo"] = custList;

                return cbdocvo.ToString();
            } 
            return "";
        }
        #endregion


        #region 同步客户档案
        /// <summary>
        /// 同步海象客户档案到U8C
        /// </summary>
        private void syncCustomer()
        {
            m_comm_MessageEvent("开始同步海象客户档案数据\n");
            string sql = "select hxid from wazh_customer where iflag = 0 ";
            string js = "";
            string errMsg = "";
            string resResult = "";
            DataTable dt = UFIDA.MYSQL.DB.DbHelperSQL.QueryAsDT(sql, common.mysqlconn());
            if (dt == null || dt.Rows.Count == 0)
            {
                U8.PUB.LogHelper.WriteLine("没有客户数据\n");
                m_comm_MessageEvent("没有客户数据\n");
                return;
            }

            foreach (DataRow dr in dt.Rows)
            {
                string code = dr["hxid"].ToString();
                m_comm_MessageEvent("客户档案" + code + "数据\n");
                js = this.getCustomerJs(code, common.mysqlconn());
                if (js.Equals(""))
                {
                    continue;
                }
                bool bpost = common.PostU8C(code, js, customerurl, ref resResult, ref errMsg);
                
                if (bpost)
                {
                    this.UpdCustomerFlag(code, 1, "", common.mysqlconn());
                }
                else
                {
                    this.UpdCustomerFlag(code, 0, errMsg, common.mysqlconn());
                }
            }
            m_comm_MessageEvent("同步海象客户档案数据完成\n");
        }


        private void UpdCustomerFlag(string code, int iflag, string errMsg, string conn)
        {
            string sql = "update wazh_customer set iflag = " + iflag + " , msg ='" + errMsg + "' where hxid = '" + code + "'";

            int icount = MYSQL.DB.DbHelperSQL.ExecuteSql(sql, conn);

        }

        private string getCustomerJs(string code, string u8conn)
        {
            string sql = "select * from vw_u8c_customer where hxid = '" + code + "'";
            
            DataTable dt = MYSQL.DB.DbHelperSQL.QueryAsDT(sql, u8conn);
            if (dt != null && dt.Rows.Count > 0)
            {
                JObject cbdocvo = new JObject();
                JArray custList = new JArray();
                string jsonb = JsonConvert.SerializeObject(dt); 
                JArray items = JArray.Parse(jsonb);
                JObject parentvo = new JObject();

                parentvo["parentvo"] = items[0]; 
                custList.Add(parentvo); 
                parentvo["banks"] = this.getbanks(code, u8conn);
                cbdocvo["cbdocvo"] = custList;

                return cbdocvo.ToString();
            }
            return "";
        }
         

        private JArray getbanks(string hxid, string u8conn)
        {
            string sql = "select * from vw_u8c_customerbank where hxid = '" + hxid + "'";
            
            DataTable dt = MYSQL.DB.DbHelperSQL.QueryAsDT(sql, u8conn);
            if (dt != null && dt.Rows.Count > 0)
            { 
                string jsonb = JsonConvert.SerializeObject(dt);
                JArray items = JArray.Parse(jsonb); 
                return items;
            }
            return null;
        }

        private JArray getsupbanks(string hxid, string u8conn)
        {
            string sql = "select * from vw_u8c_supplierbank where hxid = '" + hxid + "'";

            DataTable dt = MYSQL.DB.DbHelperSQL.QueryAsDT(sql, u8conn);
            if (dt != null && dt.Rows.Count > 0)
            {
                string jsonb = JsonConvert.SerializeObject(dt);
                JArray items = JArray.Parse(jsonb);
                return items;
            }
            return null;
        }
        #endregion


        #region 同步项目档案
        /// <summary>
        /// 同步海象项目到U8C
        /// </summary>
        private void syncProject()
        {
            m_comm_MessageEvent("开始同步海象项目数据\n");
            string sql = "select project from wazh_project where iflag = 0 "; 
            string js = "";
            string errMsg = "";
            string resResult = "";
            DataTable dt = UFIDA.MYSQL.DB.DbHelperSQL.QueryAsDT(sql, common.mysqlconn());
            if (dt== null || dt.Rows.Count == 0)
            {
                U8.PUB.LogHelper.WriteLine("没有项目数据\n");
                m_comm_MessageEvent("没有项目数据\n");
                return;
            }

            foreach (DataRow dr in dt.Rows)
            {
                string project = dr["project"].ToString();
                U8.PUB.LogHelper.WriteLine("项目" + project + "数据\n");
                js = this.getProjectJs(project, common.mysqlconn());
                if (js.Equals(""))
                {
                    continue;
                }
                bool bpost = common.PostU8C(project, js, projecturl, ref resResult, ref errMsg);
                if (bpost)
                {
                    this.UpdProjectFlag(project, 1, "", common.mysqlconn());
                }
                else
                {
                    this.UpdProjectFlag(project, 0, errMsg, common.mysqlconn());
                }
            }
            m_comm_MessageEvent("同步海象项目数据完成\n");
        }

        private void UpdProjectFlag(string project, int iflag, string errMsg, string conn)
        {
            string sql = "update wazh_project set iflag = " + iflag + " , msg ='"+ errMsg +"' where project = '"+ project + "'";
            
            int icount = MYSQL.DB.DbHelperSQL.ExecuteSql(sql, conn);

        }

        private string getProjectJs(string project, string u8conn)
        {
            string sql = "select * from vw_u8c_project where jobcode = '" + project + "'";
            
            DataTable dt = MYSQL.DB.DbHelperSQL.QueryAsDT(sql, u8conn);
            if (dt!= null && dt.Rows.Count > 0)
            {
                string json = "{\"jobbasfils\":" + JsonConvert.SerializeObject(dt) + "}";
                return json;
            }
            return "";
        }
        #endregion


        /// <summary>
        /// 回单文件下载
        /// </summary>
        /// <param name="accid"></param>
        /// <param name="connstr"></param>
        private void PostQueryReceipt(string accid, string connstr)
        {
            string js = "";
            string res = "";
            try
            {
                U8.PUB.LogHelper.WriteLine("开始下载帐户水单\n");
                List<queryaccdetailsList> mlist = UFIDA.U8C.AnLianDB.DAL.cust_queryaccdetail.GetModelWhere(" and fileflag = 0", connstr);
                if (mlist!= null )
                {
                    foreach (var item in mlist)
                    {
                        #region 回单查询
                        //获取回单 downloadNo JS
                        if (string.IsNullOrEmpty(item.serialNo))
                        {
                            U8.PUB.LogHelper.WriteLine(" 流水serialNo为空" + item.serialNo + "\n");
                            //更新标志
                            UFIDA.U8C.AnLianDB.DAL.cust_queryaccdetail.UpdateFileFlag(item.serialId, connstr, 2);
                            continue;
                        }
                        //根据item.serialId获取Receipt信息，如果没有由请求
                        
                        if (!UFIDA.U8C.AnLianDB.DAL.cust_queryReceipt.Exists(item.serialId, connstr))
                        {
                            js = this.getReceiptJs(item.serialNo, item.bankAcc);
                            if (string.IsNullOrEmpty(js))
                            {
                                continue;
                            }
                            U8.PUB.LogHelper.WriteLine(" queryReceipt请求json" + js + "\n");
                            res = NbcbSDK.send("", "accInfo", "queryReceipt", js);
                            if (string.IsNullOrEmpty(res))
                            {
                                U8.PUB.LogHelper.WriteLine("没有获取到" + item.voucherNo + "回单数据\n");
                                continue;
                            }

                            U8.PUB.LogHelper.WriteLine(" queryReceipt响应报文" + res + "\n");
                            //回单查询接口
                            queryReceiptResponse receipt = JsonConvert.DeserializeObject<queryReceiptResponse>(res);
                            if (receipt == null || receipt.Data == null || string.IsNullOrEmpty(receipt.Data.downloadNo))
                            {
                                U8.PUB.LogHelper.WriteLine("没有获取到" + item.voucherNo + "回单下载数据\n");
                                continue;
                            }

                            #region 回单文件下载
                            //获取文件下载地址请求参数
                            js = this.getDownreqJs(receipt.Data.downloadNo);
                            U8.PUB.LogHelper.WriteLine(" downLoad请求json" + js + "\n");
                            res = NbcbSDK.send("", "downLoad", "getGeneralDownloadUrl", js);
                            if (string.IsNullOrEmpty(res))
                            {
                                U8.PUB.LogHelper.WriteLine("没有获取到" + item.voucherNo + "文件下载数据\n");
                                continue;
                            }
                            DownloadResponse resp = JsonConvert.DeserializeObject<DownloadResponse>(res);
                            U8.PUB.LogHelper.WriteLine(" downLoad响应报文" + res + "\n");
                            if (resp != null && resp.Data != null)
                            {
                                this.SaveQueryReceipt(receipt.Data, resp.Data, item, connstr);
                            }
                            else
                            {
                                U8.PUB.LogHelper.WriteLine("没有获取到" + item.voucherNo + "文件下载Url\n");
                                //更新下载成功标志
                                //UFIDA.U8.WAZH.DB.DAL.cust_queryaccdetail.UpdateFileFlag(item.serialId, connstr);
                            }

                            #endregion
                        }
                        else
                        {
                            cust_queryReceipt model = UFIDA.U8C.AnLianDB.DAL.cust_queryReceipt.GetModel(item.serialId, connstr);
                            if (!string.IsNullOrEmpty(model.downloadUrl))
                            {
                                //下载文件 
                                //bool bload = Common.DownLoadFile(model.path, model.fileid, model.downloadUrl);
                                //if (bload)
                                //{
                                    //bool badd = UFIDA.U8.WAZH.DB.DAL.cust_queryReceipt.Add(model, connstr);
                                    //if (badd)
                                    //{
                                        //更新下载成功标志
                                UFIDA.U8C.AnLianDB.DAL.cust_queryaccdetail.UpdateFileFlag(item.serialId, connstr, 1);
                                    //}
                                //}
                            }
                            else
                            {
                                //获取文件下载地址请求参数
                                js = this.getDownreqJs(model.downloadNo);
                                U8.PUB.LogHelper.WriteLine(" downLoad请求json" + js + "\n");
                                res = NbcbSDK.send("", "downLoad", "getGeneralDownloadUrl", js);
                                if (string.IsNullOrEmpty(res))
                                {
                                    U8.PUB.LogHelper.WriteLine("没有获取到" + item.voucherNo + "文件下载数据\n");
                                    continue;
                                }
                                DownloadResponse resp = JsonConvert.DeserializeObject<DownloadResponse>(res);
                                U8.PUB.LogHelper.WriteLine(" downLoad响应报文" + res + "\n");
                                if (resp != null && resp.Data != null && !string.IsNullOrEmpty(resp.Data.downloadUrl))
                                {
                                    model.downloadUrl = resp.Data.downloadUrl;
                                    bool bupd = UFIDA.U8C.AnLianDB.DAL.cust_queryReceipt.Upd(model, connstr);
                                    ////下载文件 
                                    //bool bload = Common.DownLoadFile(model.path, model.fileid, resp.Data.downloadUrl);
                                    //if (bload)
                                    //{ 
                                    //    //更新下载成功标志
                                    //    UFIDA.U8.WAZH.DB.DAL.cust_queryaccdetail.UpdateFileFlag(item.serialId, connstr, 1); 
                                    //}
                                }
                                else
                                { 
                                    if (resp.Data.transMsg.Equals("无回单信息"))
                                    {
                                        model.downloadUrl = "无回单信息";
                                    }
                                    bool badd = UFIDA.U8C.AnLianDB.DAL.cust_queryReceipt.Upd(model, connstr);
                                    if (resp.Data.transState.Equals("1"))
                                    {
                                        //更新下载成功标志
                                        UFIDA.U8C.AnLianDB.DAL.cust_queryaccdetail.UpdateFileFlag(item.serialId, connstr, 2);
                                    } 
                                }
                            }
                        }
                        
                       
                        #endregion

                        
                    }
                }
                U8.PUB.LogHelper.WriteLine("完成下载帐户水单\n");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
         

        /// <summary>
        /// queryReceiptRequestData JSON
        /// </summary>
        /// <param name="vouchNo"></param>
        /// <returns></returns>
        private string getReceiptJs(string vouchNo, string bankacc)
        {
            EasyApiRequest api = new EasyApiRequest();
            queryReceiptRequestData req = new queryReceiptRequestData();
            req.custId =custID;
            req.queryFlag = "3";
            req.serialNo = vouchNo;
            req.beginDate = "";
            req.endDate = "";
            req.accountSet = new List<string>();
            req.accountSet.Add(bankacc);
            api.Data = req;

            return api.ToJson();
        }

        /// <summary>
        /// 保存回单文件到本地
        /// </summary>
        /// <param name="receipt"></param>
        /// <param name="resp"></param>
        /// <param name="item"></param>
        /// <param name="connstr"></param>
        private void SaveQueryReceipt(queryReceiptResponData receipt, DownloadRespData resp, queryaccdetailsList item, string connstr)
        {
            //回单文件子表 Model
            cust_queryReceipt model = new cust_queryReceipt();
            model.downloadNo = receipt.downloadNo;
            model.downloadUrl = resp.downloadUrl;
            model.fileid = System.IO.Path.GetFileName(model.downloadUrl);
            model.path = sPath;
            model.serialid = item.serialId;
            model.serialNo = item.serialNo;

            if (!string.IsNullOrEmpty(resp.downloadUrl))
            {
                    
                bool badd = UFIDA.U8C.AnLianDB.DAL.cust_queryReceipt.Add(model, connstr);
                if (resp.transState.Equals("1"))
                {
                    //更新下载成功标志
                    UFIDA.U8C.AnLianDB.DAL.cust_queryaccdetail.UpdateFileFlag(item.serialId, connstr, 2);
                } 
            }
            else
            {
                if (resp.transMsg.Equals("无回单信息"))
                {
                    model.downloadUrl = "无回单信息";
                }
                bool badd = UFIDA.U8C.AnLianDB.DAL.cust_queryReceipt.Add(model, connstr);
                if (resp.transState.Equals("1"))
                {
                    //更新下载成功标志
                    UFIDA.U8C.AnLianDB.DAL.cust_queryaccdetail.UpdateFileFlag(item.serialId, connstr, 2);
                }
            }

            //下载文件 
            //bool bload = Common.DownLoadFile(model.path, model.fileid, model.downloadUrl);
            //if (bload)
            //{
            //    bool badd = UFIDA.U8.WAZH.DB.DAL.cust_queryReceipt.Add(model, connstr);
            //    if (badd)
            //    {
            //        //更新下载成功标志
            //        UFIDA.U8.WAZH.DB.DAL.cust_queryaccdetail.UpdateFileFlag(item.serialId, connstr, 1);
            //    }
            //} 
        } 

        /// <summary>
        /// //获取文件下载地址请求参数
        /// </summary>
        /// <param name="downloadno">下载编号</param>
        /// <returns></returns>
        private string getDownreqJs(string downloadno)
        {
            EasyApiRequest api = new EasyApiRequest();
            DownloadResqData downreq = new DownloadResqData();
            downreq.downloadNo = downloadno;
            downreq.custId = custID;
            downreq.tradeType = "RECEIPT";// "RECEIPT"; 
            api.Data = downreq;
            return api.ToJson();
        }

        /// <summary>
        /// 交易明细下载
        /// </summary>
        /// <param name="accid"></param>
        /// <param name="tragetconnectstring"></param>
        private void PostAccDetail(string accid, string tragetconnectstring)
        {
            string lasttime;  //上次请求完成时间戳 
            string curtime = dtCurDate.Text;
            try
            {
                DataTable ds = this.selectAccountTime(accid);
                if (ds!= null && ds.Rows.Count > 0)
                {
                    foreach (DataRow dr in ds.Rows)
                    {
                        if (!string.IsNullOrEmpty(curtime))
                        {
                            lasttime = curtime.ObjToDateTime().ToString("yyyy-MM-dd");
                        }
                        else
                        {
                            lasttime = dr["dsynctime"].ObjToDateTime().ToString("yyyy-MM-dd");
                        }
                        
                        accountcode = dr["record"].ToString();
                        if (string.IsNullOrEmpty(accountcode))
                        {
                            continue;
                        }
                        m_comm_MessageEvent("开始下载" + accountcode + "数据,上次完成时间" + lasttime + "\n");
                        U8.PUB.LogHelper.WriteLine("开始下载" + accountcode + "数据,上次完成时间" + lasttime + "\n");


                        //完整JSON
                        String dataJson = this.getqueryAccDetailJs(ref lasttime);
                        U8.PUB.LogHelper.WriteLine(" 请求json" + dataJson + "\n");
                        // 发送请求并获取响应
                        //string res = NbcbSDK.send("", "accInfo", "queryAccount", dataJson);
                        //U8.PUB.LogHelper.WriteLine(" queryAccount返回json" + res + "\n");
                        //dataJson = "{\"Data\":{\"custId\":\"0000156566\",\"bankAccList\":[\"77010122000031318\"],\"currentPage\":\"1\",\"pageSize\":\"1000\",\"queryType\":\"0\",\"beginDate\":\"2021-06-01\",\"endDate\":\"2021-07-01\",\"cdSign\":\"\",\"beginAmt\":\"\",\"endAmt\":\"\"}}";

                        string res = NbcbSDK.send("", "accInfo", "queryAccDetail", dataJson);
                        U8.PUB.LogHelper.WriteLine(" queryAccDetail返回json" + res + "\n");

                        EasyApiResponse respone = JsonConvert.DeserializeObject<EasyApiResponse>(res);

                        if (string.IsNullOrEmpty(res) || respone.Data==null || !respone.Data.retCode.Equals("0000"))
                        {
                            U8.PUB.LogHelper.WriteLine("没有下载到" + accountcode + "数据,上次完成时间" + lasttime + "\n");
                            m_comm_MessageEvent("没有下载到" + accountcode + "数据,上次完成时间" + lasttime + "\n");

                            //更新时间戳    
                            this.updAccountTime(accid, lasttime, accountcode);
                            m_comm_MessageEvent(DateTime.Now + ":更新帐号" + accountcode + "时间戳完成\n");
                            continue;
                        }

                        //保存数据
                        this.SaveAccDetailData(res, _connectstring);

                        //更新时间戳    
                        this.updAccountTime(accid, lasttime, accountcode);
                        m_comm_MessageEvent(DateTime.Now + ":更新帐号" + accountcode + "时间戳完成\n");
                 
                    }
                } 
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        /// <summary>
        /// 交易明细存入数据库
        /// </summary>
        /// <param name="res">json</param>
        /// <param name="tragetconnectstring">目标数据库</param>
        private void SaveAccDetailData(string res, string conn)
        {

            List<CommandInfo> cmdlist = new List<CommandInfo>();
            try
            {
                EasyApiResponse response = JsonConvert.DeserializeObject<EasyApiResponse>(res);
                if (response !=null)
                {
                    queryAccDetailResponData data =  response.Data;
                    if (data!=null && data.list!=null)
                    {
                        cmdlist = this.getAccDetailAddCommand(data.list, conn);
                        if (cmdlist.Count > 0)
                        {
                            UFIDA.U8.DB.DbHelperSQL.ExecuteSqlTran(cmdlist, conn);
                            U8.PUB.LogHelper.WriteLine("交易明细存入后台" + res + "\n");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        /// <summary>
        /// 水单下载按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFileDown_Click(object sender, EventArgs e)
        {
            string accid = edtacc.Text;
            if (string.IsNullOrEmpty(accid))
            {
                MessageBox.Show("请选择目标帐套");
                return;
            }
            if (!string.IsNullOrEmpty(tragetconnectstring))
	        {
                PostQueryReceipt(accid, tragetconnectstring);
	        } 
        }

        /// <summary>
        /// 交易明细数据库脚本组织
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        private List<CommandInfo> getAccDetailAddCommand(List<queryaccdetailsList> list, string connstr)
        {
            List<CommandInfo> cmdlist = new List<CommandInfo>();
            foreach (var item in list)
            {
                if (!UFIDA.U8C.AnLianDB.DAL.cust_queryaccdetail.Exists(item.serialId, connstr))
                { 
                    cmdlist.Add(UFIDA.U8C.AnLianDB.DAL.cust_queryaccdetail.GetAddCommand(item));
                }
            }
            return cmdlist;
        }


        public static bool isToday(DateTime dt)
        {
            DateTime today = DateTime.Today;
            DateTime tempToday = new DateTime(dt.Year, dt.Month, dt.Day);
            if (today == tempToday)
                return true;
            else
                return false;
        }
        /// <summary>
        /// 组织交易查询json
        /// </summary>
        /// <param name="lasttime"></param>
        /// <returns></returns>
        private String getqueryAccDetailJs(ref string lasttime)
        {
            EasyApiRequest apireq = new EasyApiRequest();
            
            queryAccDetailRequestData model = new queryAccDetailRequestData();
            model.custId = this.custID;
            model.bankAccList = new List<string>();
            model.bankAccList.Add(accountcode);
            model.beginDate = lasttime.ObjToDateTime().ToString("yyyy-MM-dd");
           
            model.endDate = ""; 
            model.pageSize = "1000";
            model.queryType = "0";
            model.currentPage = "1";
            model.beginAmt = "";
            model.endAmt = "";
            model.cdSign = "";
            apireq.Data = model;
            if (isToday(lasttime.ObjToDateTime()))
            {
                
            }
            else
            {
                lasttime = lasttime.ObjToDateTime().AddDays(1).ToString("yyyy-MM-dd");
            }
            
            return apireq.ToJson();
            
        }
 
        /// <summary>
        /// 更新帐套最新同步时间
        /// </summary>
        /// <param name="id"></param>
        /// <param name="dcurtime"></param>
        /// <param name="record"></param>
        /// <returns></returns>
        private int updAccountTime(string id, string lasttime, string record)
        {
            string sql = "update cust_accconfig set dsynctime = '" + lasttime + "' where record='" + record + "'";
            return DbHelperSQL.ExecuteSql(sql, _connectstring);
        }

        /// <summary>
        /// 获取帐套上次同步时间
        /// </summary>
        /// <param name="id"></param>
        /// <param name="record"></param>
        /// <returns></returns>
        private DataTable selectAccountTime(string accid)
        {
            string sql = "select * from cust_accconfig where accid = '" + accid  + "' ";
            return DbHelperSQL.QueryAsDT(sql, _connectstring);
        }

        /// <summary>
        /// 获取帐套信息
        /// </summary>
        /// <returns></returns>
        private DataTable getaccountInfo()
        {
            string sql = "select * from cust_syncacount where flag = 1";
            return DbHelperSQL.QueryAsDT(sql, _connectstring);
        }
        #endregion
         
        #region 作废代码 by fulj 20220408 
        private void buttonItem1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.edtacc.Text))
            {
                MessageBox.Show("请选择目标帐套");
                return;
            }
            accid = this.edtacc.Text;

            int tabindex = tabControl1.SelectedTabIndex;
            try
            {
                this.Cursor = Cursors.WaitCursor;
                switch (tabindex)
                {
                    case 1:
                        //this.syncCustomer(tragetconnectstring);
                        break;
                    case 2:
                        //this.syncVendor(tragetconnectstring);
                        break;
                    case 3:
                        //this.syncInventory(tragetconnectstring);
                        break;
                    case 4:
                        //this.syncProuting(tragetconnectstring);
                        break;
                    case 5:
                        //this.syncBom(tragetconnectstring);
                        break;
                    case 6:
                        //this.syncDetail(tragetconnectstring);
                        break;
                    case 7:
                        //this.syncWB(tragetconnectstring);
                        break;
                }
            }
            catch (Exception ex)
            {
                U8.PUB.LogHelper.WriteLine(ex.Message);
                MessageBox.Show(ex.Message);
                //this.buttonX2_Click(sender, e);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void btnworkcenter_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tragetconnectstring))
            {
                MessageBox.Show("请选择目标帐套");
                return;
            }
            List<UFIDA.U8.DB.Model.sfc_workcenter> Models = new List<U8.DB.Model.sfc_workcenter>();
            List<UFIDA.U8.DB.CommandInfo> sqllist = new List<UFIDA.U8.DB.CommandInfo>();
            UFIDA.U8.DB.CommandInfo cmd;

            try
            {
                this.Cursor = Cursors.WaitCursor;

                Models = UFIDA.U8.DB.DAL.sfc_workcenter.GetModel("", "");
                if (Models != null && Models.Count > 0)
                {
                    U8.PUB.LogHelper.WriteLine("读取工作中心数据:" + Models.Count);

                    U8.PUB.LogHelper.WriteLine("组织工作中心数据cmd");
                    foreach (UFIDA.U8.DB.Model.sfc_workcenter operation in Models)
                    {
                        if (!UFIDA.U8.DB.DAL.sfc_workcenter.Exists(operation.WcId, tragetconnectstring))
                        {
                            cmd = UFIDA.U8.DB.DAL.sfc_workcenter.GetAddCommand(operation);
                            sqllist.Add(cmd);
                        }
                        else
                        {
                            cmd = UFIDA.U8.DB.DAL.sfc_workcenter.GetUpdCommand(operation);
                            sqllist.Add(cmd);
                        }
                    }
                    U8.PUB.LogHelper.WriteLine("插入工作中心数据");
                    if (sqllist.Count > 0)
                    {
                        DbHelperSQL.ExecuteSqlTran(sqllist, tragetconnectstring);
                        MessageBox.Show("程序执行结束, 插入或更新" + sqllist.Count + "条工作中心数据"); //，可以查询U8SOFT\\Logs\\目录下日志，是否有错误信息
                    }
                }
                else
                {
                    MessageBox.Show("没有工作中心数据");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }


        #endregion 

        private void SyncUI_Load(object sender, EventArgs e)
        {
            btnStart_Click(sender, e);
        }

        private void btnSyncHX_Click(object sender, EventArgs e)
        {
            this.syncHx();
        }

       
        
        #region liny20210830:注释掉用不到的代码

        /// <summary>
        /// 单独同步供应商档案
        /// </summary>
        /// <param name="tragetconnectstring"></param>
        //private void syncVendor(string tragetconnectstring)
        //{
        //    dsvendor.AcceptChanges();
        //    try
        //    {
        //        if (dgvvendor.RowCount > 0)
        //        {
        //            DataRow[] rows = dsvendor.Tables[0].Select("ischeck=1");

        //            if (rows != null && rows.Length > 0)
        //            {
        //                //this.syncVendorData(dsvendor.Tables[0].Rows);
        //                MessageBox.Show("程序执行结束");
        //            }
        //            else
        //            {
        //                MessageBox.Show("请先选择明细信息");
        //            }

        //        }
        //        else
        //        {
        //            MessageBox.Show("明细信息空");
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        throw e;
        //    }
        //}

        /// <summary>
        /// 自定义项同步 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void btnUserdef_Click(object sender, EventArgs e)
        //{
        //    if (string.IsNullOrEmpty(tragetconnectstring))
        //    {
        //        MessageBox.Show("请选择目标帐套");
        //        return;
        //    }
        //    try
        //    {
        //        this.Cursor = Cursors.WaitCursor;
        //        List<UFIDA.U8.DB.Model.UserDefine> Models = new List<DB.Model.UserDefine>();
        //        UFIDA.U8.DB.Model.UserDefine model;
        //        List<UFIDA.U8.DB.CommandInfo> sqllist = new List<UFIDA.U8.DB.CommandInfo>();
        //        UFIDA.U8.DB.CommandInfo cmd;

        //        DataSet ds = UFIDA.U8.DB.DAL.UserDefine.GetList("", "");
        //        if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
        //        {
        //            U8.PUB.LogHelper.WriteLine("读取自定义项数据:" + ds.Tables[0].Rows.Count);
        //            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        //            {
        //                model = UFIDA.U8.DB.DAL.UserDefine.DataRowToModel(ds.Tables[0].Rows[i]);
        //                Models.Add(model);
        //            }

        //            foreach (UFIDA.U8.DB.Model.UserDefine userdefine in Models)
        //            {
        //                if (!UFIDA.U8.DB.DAL.UserDefine.Exists(userdefine.cID, userdefine.cValue, tragetconnectstring))
        //                {
        //                    cmd = UFIDA.U8.DB.DAL.UserDefine.GetAddCommand(userdefine);
        //                    sqllist.Add(cmd);
        //                }
        //            }

        //            if (sqllist.Count > 0)
        //            {
        //                DbHelperSQL.ExecuteSqlTran(sqllist, tragetconnectstring);
        //                MessageBox.Show("程序执行结束，插入或更新" + sqllist.Count + "条自定义项数据"); //，可以查询U8SOFT\\Logs\\目录下日志，是否有错误信息
        //            }
        //        }
        //        else
        //        {
        //            MessageBox.Show("没有自定义项数据");
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show(ex.Message);
        //    }
        //    finally
        //    {
        //        this.Cursor = Cursors.Default;
        //    }
        //}

        /// <summary>
        /// 标准工序同步
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void btnopera_Click(object sender, EventArgs e)
        //{
        //    if (string.IsNullOrEmpty(tragetconnectstring))
        //    {
        //        MessageBox.Show("请选择目标帐套");
        //        return;
        //    }
        //    List<UFIDA.U8.DB.Model.sfc_operation> Models = new List<DB.Model.sfc_operation>();
        //    List<UFIDA.U8.DB.CommandInfo> sqllist = new List<UFIDA.U8.DB.CommandInfo>();
        //    List<UFIDA.U8.DB.CommandInfo> cmd;

        //    try
        //    {
        //        this.Cursor = Cursors.WaitCursor;
        //        Models = UFIDA.U8.DB.DAL.sfc_operation.GetListModel("", "");
        //        if (Models != null && Models.Count > 0)
        //        {
        //            U8.PUB.LogHelper.WriteLine("读取标准工序数据:" + Models.Count);

        //            U8.PUB.LogHelper.WriteLine("组织标准工序数据cmd");
        //            foreach (UFIDA.U8.DB.Model.sfc_operation operation in Models)
        //            {
        //                if (!UFIDA.U8.DB.DAL.sfc_operation.Exists(operation.OperationId, tragetconnectstring))
        //                {
        //                    cmd = UFIDA.U8.DB.DAL.sfc_operation.GetAddCommand(operation);
        //                    sqllist.AddRange(cmd);
        //                }
        //                else
        //                {
        //                    cmd = UFIDA.U8.DB.DAL.sfc_operation.GetUpdCommand(operation, tragetconnectstring);
        //                    sqllist.AddRange(cmd);
        //                }
        //            }
        //            U8.PUB.LogHelper.WriteLine("插入标准工序数据");
        //            if (sqllist.Count > 0)
        //            {
        //                DbHelperSQL.ExecuteSqlTran(sqllist, tragetconnectstring);
        //                MessageBox.Show("程序执行结束，插入或更新" + sqllist.Count + "条标准工序数据"); //，可以查询U8SOFT\\Logs\\目录下日志，是否有错误信息
        //            }
        //        }
        //        else
        //        {
        //            MessageBox.Show("没有标准工序数据");
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show(ex.Message);
        //    }
        //    finally
        //    {
        //        this.Cursor = Cursors.Default;
        //    }
        //}

        /// <summary>
        /// 同步BOM Data
        /// </summary>
        /// <param name="value"></param>
        /// <param name="u8connectstring"></param>
        /// <param name="tragetconnect"></param>
        /// <param name="icount"></param>
        //private void syncBomData(int bomid, string u8connectstring, string tragetconnect, ref int icount)
        //{
        //    List<UFIDA.U8.DB.CommandInfo> sqllist = new List<UFIDA.U8.DB.CommandInfo>();
        //    List<UFIDA.U8.DB.CommandInfo> cmd;
        //    UFIDA.U8.DB.Model.bom_bom model;

        //    model = UFIDA.U8.DB.DAL.bom_bom.GetModel(bomid, u8connectstring);

        //    if (UFIDA.U8.DB.DAL.bom_bom.Exists(bomid, tragetconnect))
        //    {
        //        cmd = UFIDA.U8.DB.DAL.bom_bom.GetUpdCommand(model, tragetconnect);
        //    }
        //    else
        //    {
        //        cmd = UFIDA.U8.DB.DAL.bom_bom.GetAddCommand(model);
        //    }

        //    sqllist = cmd;

        //    if (sqllist.Count > 0)
        //    {
        //        icount += 1;
        //        DbHelperSQL.ExecuteSqlTran(sqllist, tragetconnect);
        //    }
        //}

        /// <summary>
        /// 查询供应商
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void buttonX2_Click(object sender, EventArgs e)
        //{
        //    string sql = this.getSuppliersql(corp);

        //    try
        //    {
        //        //string oracleconnstring = "Data Source=orclnc;Persist Security Info=True;User ID=fthw;Password=fthw;";//Provider=OraOLEDB.Oracle;Data Source=orclnc;User Id=fthw;Password=fthw; ";
        //        //dsvendor = NC.DB.DAL.BD_SUPPLIER.GetList(sql, NcConnectstring);
        //        bdsvendor.DataSource = null;
        //        bdsvendor.DataSource = dsvendor;
        //        bdsvendor.DataMember = "Table";
        //        vcount.Text = bdsvendor.Count.ToString();
        //    }
        //    catch (Exception ex)
        //    {
        //        U8.PUB.LogHelper.WriteLine(this.GetType() + ":" + ex.Message);
        //        MessageBox.Show(ex.Message);
        //    }
        //}

        //private string getSuppliersql(string corp)
        //{
        //    StringBuilder sql = new StringBuilder();

        //    //and ( pk_supplier in 
        //    //( select pk_supplier from bd_suporg where pk_org in ( '0001F110000000005E69' ) and enablestate = 2 
        //    // union select pk_supplier from bd_supplier where ( pk_org = '0001F110000000000E60' or  pk_org = '0001F110000000005E69' ) ) ) 
        //    //order by code desc

        //    sql.Append(" pk_supplier in ( select pk_supplier from bd_suporg where pk_org in ( '" + corp + "' ) and enablestate = 2  union select pk_supplier from bd_supplier where  pk_org = '" + corp + "'  ) ");

        //    //供应商编码
        //    if (!string.IsNullOrEmpty(edtcvencode.Text))
        //    {
        //        sql.Append(" and code like '%" + edtcvencode.Text.ToString() + "%'");
        //    }
        //    //供应商名称
        //    if (!string.IsNullOrEmpty(edtcvenname.Text))
        //    {
        //        sql.Append(" and name like '%" + edtcvenname.Text.ToString() + "%'");
        //    }
        //    //创建日期
        //    if (!string.IsNullOrEmpty(dtSupAddDate1.Text))
        //    {
        //        sql.Append(" and creationtime >= '" + dtSupAddDate1.Text.ToString() + "'");
        //    }
        //    if (!string.IsNullOrEmpty(dtSupAddDate2.Text))
        //    {
        //        sql.Append(" and creationtime <= '" + dtSupAddDate2.Text.ToString() + "'");
        //    }
        //    //修改日期
        //    if (!string.IsNullOrEmpty(dtSupModifyDate1.Text))
        //    {
        //        sql.Append(" and modifiedtime >= '" + dtSupModifyDate1.Text.ToString() + "'");
        //    }
        //    if (!string.IsNullOrEmpty(dtSupModifyDate2.Text))
        //    {
        //        sql.Append(" and modifiedtime <= '" + dtSupModifyDate2.Text.ToString() + "'");
        //    }

        //    return sql.ToString();
        //}

        //private void syncCustomer(string tragetconnectstring)
        //{
        //    dscustomer.AcceptChanges();
        //    try 
        //    {
        //        if (dgvcustomer.RowCount > 0)
        //        {
        //            DataRow[] rows = dscustomer.Tables[0].Select("ischeck=1");

        //            if (rows != null && rows.Length > 0)
        //            {
        //                this.syncCustomerData(dscustomer.Tables[0].Rows);
        //                MessageBox.Show("程序执行结束");
        //            }
        //            else
        //            {
        //                MessageBox.Show("请先选择明细信息");
        //            }    
        //        }
        //        else
        //        {
        //            MessageBox.Show("明细信息空");
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        throw e;
        //    }            
        //}

        /// <summary>
        /// 组织客户联系人新增脚本
        /// </summary>
        /// <param name="linkman"></param>
        /// <param name="p"></param>
        /// <param name="tragetconnectstring"></param>
        /// <returns></returns>
        //private CommandInfo getCrm_ContactrAdd(NC.DB.Model.BD_CUSTLINKMAN linkman, string cCusCode, string tragetconnectstring)
        //{
        //    CommandInfo cmd = null;
        //    try
        //    {
        //        UFIDA.U8.DB.Model.Crm_Contact model = new DB.Model.Crm_Contact();
        //        model.cCusCode = cCusCode;
        //        model.cContactCode = linkman.LINKMAN.CODE;
        //        model.cContactName = linkman.LINKMAN.NAME;
        //        model.cMobilePhone = linkman.LINKMAN.PHONE;
        //        model.cOfficePhone = linkman.LINKMAN.PHONE;
        //        model.cEmail = linkman.LINKMAN.EMAIL;
        //        model.cMemo = linkman.LINKMAN.MEMO;
        //        model.cCreator = "NC";
        //        model.dCreateDate = DateTime.Now;
        //        model.OID = "{" + Guid.NewGuid().ToString() + "}";

        //        cmd = UFIDA.U8.DB.DAL.Crm_Contact.GetAddCommand(model);
        //        return cmd;
        //    }
        //    catch (Exception ex)
        //    {
        //        U8.PUB.LogHelper.WriteLine(ex.ToString());
        //        throw ex;
        //    }
        //}

        /// <summary>
        /// 组织客户联系人更新脚本
        /// </summary>
        /// <param name="linkman"></param>
        /// <param name="p"></param>
        /// <param name="tragetconnectstring"></param>
        /// <returns></returns>
        //private CommandInfo getCrm_ContactrUpd(NC.DB.Model.BD_CUSTLINKMAN linkman, string cCusCode, string tragetconnectstring)
        //{
        //    CommandInfo cmd = null;
        //    try
        //    {
        //        UFIDA.U8.DB.Model.Crm_Contact model = UFIDA.U8.DB.DAL.Crm_Contact.GetModel(cCusCode, linkman.LINKMAN.CODE, tragetconnectstring);
        //        if (model != null)
        //        {
        //            model.cContactName = linkman.LINKMAN.NAME;
        //            model.cMobilePhone = linkman.LINKMAN.PHONE;
        //            model.cOfficePhone = linkman.LINKMAN.PHONE;
        //            model.cEmail = linkman.LINKMAN.EMAIL;
        //            model.cMemo = linkman.LINKMAN.MEMO;
        //            model.dModifyDate = DateTime.Now;

        //            cmd = UFIDA.U8.DB.DAL.Crm_Contact.GetUpdCommand(model);
        //        }
        //        return cmd;
        //    }
        //    catch (Exception ex)
        //    {
        //        U8.PUB.LogHelper.WriteLine(ex.ToString());
        //        throw ex;
        //    }
        //}

        /// <summary>
        /// 组织客户银行新增脚本
        /// </summary>
        /// <param name="bank"></param>
        /// <returns></returns>
        //private CommandInfo getcustBankAdd(NC.DB.Model.BD_CUSTBANK bank, string cCusCode)
        //{
        //    CommandInfo cmd = null;
        //    try
        //    {
        //        UFIDA.U8.DB.Model.CustomerBank cbank = new DB.Model.CustomerBank();
        //        cbank.cCusCode = cCusCode;
        //        cbank.cAccountNum = bank.BANKACCBAS.ACCNUM;
        //        cbank.cAccountName = bank.BANKACCBAS.ACCNAME;
        //        cbank.cBranch = bank.BANKACCBAS.BANKDOC.NAME;
        //        //cbank.cBank = bank.BANKACCBAS.BANKDOC.CODE;

        //        cmd = UFIDA.U8.DB.DAL.CustomerBank.GetUpdCommand(cbank);
        //        return cmd;
        //    }
        //    catch (Exception ex)
        //    {
        //        U8.PUB.LogHelper.WriteLine(ex.ToString());
        //        throw ex;
        //    }
        //}

        /// <summary>
        /// 组织客户银行更新脚本
        /// </summary>
        /// <param name="bank"></param>
        /// <returns></returns>
        //private CommandInfo getcustBankUpd(NC.DB.Model.BD_CUSTBANK bank)
        //{
        //    CommandInfo cmd = null;
        //    try
        //    {
        //        UFIDA.U8.DB.Model.CustomerBank cbank = UFIDA.U8.DB.DAL.CustomerBank.GetModel(bank.BANKACCBAS.ACCNUM, tragetconnectstring);
        //        if (cbank != null)
        //        {
        //            cbank.cAccountName = bank.BANKACCBAS.ACCNAME;
        //            cbank.cBranch = bank.BANKACCBAS.BANKDOC.NAME;
        //            cbank.cBank = bank.BANKACCBAS.BANKDOC.CODE;

        //            cmd = UFIDA.U8.DB.DAL.CustomerBank.GetUpdCommand(cbank);
        //        }
        //        return cmd;
        //    }
        //    catch (Exception ex)
        //    {
        //        U8.PUB.LogHelper.WriteLine(ex.ToString());
        //        throw ex;
        //    }
        //}


        /// <summary>
        /// 组织客户地址新增脚本
        /// </summary>
        /// <param name="address"></param>
        /// <param name="cCusCode"></param>
        /// <param name="tragetconnectstring"></param>
        /// <returns></returns>
        //private CommandInfo getCusDeliverAdd(NC.DB.Model.BD_CUSTADDRESS address, string cCusCode, string tragetconnectstring)
        //{
        //    CommandInfo cmd = null;
        //    try
        //    {
        //        UFIDA.U8.DB.Model.CusDeliverAdd deliver = new DB.Model.CusDeliverAdd();

        //        deliver.cCusCode = cCusCode;
        //        deliver.cAddCode = address.ADDRESS.CODE;
        //        deliver.cDeliverAdd = address.ADDRESS.DETAILINFO;
        //        deliver.bDefault = false;

        //        cmd = UFIDA.U8.DB.DAL.CusDeliverAdd.GetAddCommand(deliver);
        //        return cmd;
        //    }
        //    catch (Exception ex)
        //    {
        //        U8.PUB.LogHelper.WriteLine(ex.ToString());
        //        throw ex;
        //    }
        //}

        /// <summary>
        /// 组织客户地址更新脚本
        /// </summary>
        /// <param name="address"></param>
        /// <param name="cCusCode"></param>
        /// <param name="tragetconnectstring"></param>
        /// <returns></returns>
        //private CommandInfo getCusDeliverUpd(NC.DB.Model.BD_CUSTADDRESS address, string cCusCode, string tragetconnectstring)
        //{
        //    CommandInfo cmd = null;
        //    try
        //    {
        //        UFIDA.U8.DB.Model.CusDeliverAdd deliver = UFIDA.U8.DB.DAL.CusDeliverAdd.GetModel(cCusCode, address.ADDRESS.CODE, tragetconnectstring);
        //        if (deliver != null)
        //        {
        //            deliver.cDeliverAdd = address.ADDRESS.DETAILINFO;

        //            cmd = UFIDA.U8.DB.DAL.CusDeliverAdd.GetUpdCommand(deliver);
        //        }
        //        return cmd;
        //    }
        //    catch (Exception ex)
        //    {
        //        U8.PUB.LogHelper.WriteLine(ex.ToString());
        //        throw ex;
        //    }
        //}


        /// <summary>
        /// 组织客户基本信息新增脚本
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        //private CommandInfo getCustomerInscmd(NC.DB.Model.BD_CUSTOMER model)
        //{
        //    CommandInfo cmd = null;
        //    try
        //    {
        //        UFIDA.U8.DB.Model.Customer customer = new DB.Model.Customer();
        //        customer.cCusCode = model.CODE;
        //        customer.cCusName = model.NAME;
        //        customer.cCusAbbName = model.NAME;
        //        customer.cCusRegCode = model.TAXPAYERID;
        //        customer.cCusLPerson = model.LEGALBODY;
        //        customer.cCusEmail = model.EMAIL;
        //        customer.cCCCode = model.CUSTCLASS.CODE;

        //        customer.cCusPhone = model.TEL1;
        //        customer.cCusFax = model.FAX1;
        //        //税率  
        //        customer.iCusTaxRate = model.itaxrate;

        //        //发展日期
        //        customer.dCusDevDate = DateTime.Now.Date;

        //        //默认管理类型
        //        customer.cCusMngTypeCode = "999";
        //        //币种
        //        if (model.CURRTYPE != null)
        //        {
        //            customer.cCusExch_name = model.CURRTYPE.NAME;
        //        }

        //        //允限销控制
        //        customer.bLimitSale = true;

        //        customer.cInvoiceCompany = model.CODE;

        //        //专管部门 业务员
        //        if (model.CUSTFINANCE != null)
        //        {
        //            if (!string.IsNullOrEmpty(model.CUSTFINANCE.respdeptcode))
        //            {
        //                customer.cCusDepart = model.CUSTFINANCE.respdeptcode;
        //            }
        //            if (!string.IsNullOrEmpty(model.CUSTFINANCE.resppsncode))
        //            {
        //                customer.cCusPerson = model.CUSTFINANCE.resppsncode;
        //            }
        //            //收款协议 
        //            if (model.CUSTFINANCE.INCOM != null)
        //            {
        //                customer.cCusSAProtocol = model.CUSTFINANCE.INCOM.CODE;
        //            }
        //        }

        //        //银行信息
        //        if (model.CUSTBANKList != null && model.CUSTBANKList.Count > 0)
        //        {
        //            customer.cCusBank = model.CUSTBANKList[0].BANKACCBAS.BANKDOC.NAME;
        //            customer.cCusBankCode = model.CUSTBANKList[0].BANKACCBAS.BANKDOC.CODE;
        //            customer.cCusAccount = model.CUSTBANKList[0].BANKACCBAS.ACCNUM;
        //        }

        //        //地址
        //        if (model.CUSTADDRESSList != null && model.CUSTADDRESSList.Count > 0)
        //        {
        //            customer.cCusAddress = model.CUSTADDRESSList[0].ADDRESS.DETAILINFO;
        //        }

        //        //是否签回
        //        customer.bRequestSign = true;

        //        customer.cCusDefine1 = model.DEF1;
        //        customer.cCusDefine2 = model.DEF2;
        //        customer.cCusDefine3 = model.DEF3;
        //        customer.cCusDefine4 = model.DEF4;
        //        customer.cCusDefine5 = model.DEF5;
        //        customer.cCusDefine6 = model.DEF6;
        //        customer.cCusDefine7 = model.DEF7;
        //        customer.cCusDefine8 = model.DEF8;
        //        customer.cCusDefine9 = model.DEF9;
        //        customer.cCusDefine10 = model.DEF10;
        //        customer.cCusDefine11 = model.DEF11.ObjToInt32();
        //        customer.cCusDefine12 = model.DEF12.ObjToInt32();
        //        customer.cCusDefine13 = model.DEF13.ObjToDecimal();
        //        customer.cCusDefine14 = model.DEF14.ObjToDecimal();
        //        customer.cCusDefine15 = model.DEF15.ObjToDateTimeNull();
        //        customer.cCusDefine16 = model.DEF16.ObjToDateTimeNull();

        //        cmd = UFIDA.U8.DB.DAL.Customer.GetAddCommand(customer);

        //        return cmd;
        //    }
        //    catch (Exception ex)
        //    {
        //        U8.PUB.LogHelper.WriteLine(ex.ToString());
        //        throw ex;
        //    }
        //}

        /// <summary>
        /// 组织客户基本信息更新脚本
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        //private CommandInfo getCustomerUpdcmd(NC.DB.Model.BD_CUSTOMER model)
        //{
        //    CommandInfo cmd = null;
        //    try
        //    {
        //        UFIDA.U8.DB.Model.Customer customer = UFIDA.U8.DB.DAL.Customer.GetModel(model.CODE, tragetconnectstring);
        //        if (customer != null)
        //        {
        //            customer.cCusName = model.NAME;
        //            customer.cCusAbbName = model.NAME;
        //            customer.cCusRegCode = model.TAXPAYERID;
        //            customer.cCusLPerson = model.LEGALBODY;
        //            customer.cCusEmail = model.EMAIL;
        //            customer.cCCCode = model.CUSTCLASS.CODE;
        //            //税率
        //            customer.iCusTaxRate = model.itaxrate;
        //            //币种
        //            if (model.CURRTYPE != null)
        //            {
        //                customer.cCusExch_name = model.CURRTYPE.NAME;
        //            }

        //            //联系人
        //            if (model.CUSTLINKMANList != null && model.CUSTLINKMANList.Count > 0)
        //            {
        //                customer.cCusPerson = model.CUSTLINKMANList[0].LINKMAN.NAME;
        //                customer.cCusPhone = model.CUSTLINKMANList[0].LINKMAN.PHONE;
        //                customer.cCusFax = model.CUSTLINKMANList[0].LINKMAN.FAX;
        //            }

        //            //专管部门 业务员
        //            if (model.CUSTFINANCE != null)
        //            {
        //                if (!string.IsNullOrEmpty(model.CUSTFINANCE.respdeptcode))
        //                {
        //                    customer.cCusDepart = model.CUSTFINANCE.respdeptcode;
        //                }
        //                if (!string.IsNullOrEmpty(model.CUSTFINANCE.resppsncode))
        //                {
        //                    customer.cCusPPerson = model.CUSTFINANCE.resppsncode;
        //                }
        //                //收款协议 
        //                if (model.CUSTFINANCE.INCOM != null)
        //                {
        //                    customer.cCusSAProtocol = model.CUSTFINANCE.INCOM.CODE;
        //                }
        //            }

        //            //银行信息
        //            if (model.CUSTBANKList != null && model.CUSTBANKList.Count > 0)
        //            {
        //                customer.cCusBank = model.CUSTBANKList[0].BANKACCBAS.BANKDOC.NAME;
        //                customer.cCusBankCode = model.CUSTBANKList[0].BANKACCBAS.BANKDOC.CODE;
        //                customer.cCusAccount = model.CUSTBANKList[0].BANKACCBAS.ACCNUM;
        //            }

        //            //地址
        //            if (model.CUSTADDRESSList != null && model.CUSTADDRESSList.Count > 0)
        //            {
        //                customer.cCusAddress = model.CUSTADDRESSList[0].ADDRESS.DETAILINFO;
        //            }


        //            customer.cCusDefine1 = model.DEF1;
        //            customer.cCusDefine2 = model.DEF2;
        //            customer.cCusDefine3 = model.DEF3;
        //            customer.cCusDefine4 = model.DEF4;
        //            customer.cCusDefine5 = model.DEF5;
        //            customer.cCusDefine6 = model.DEF6;
        //            customer.cCusDefine7 = model.DEF7;
        //            customer.cCusDefine8 = model.DEF8;
        //            customer.cCusDefine9 = model.DEF9;
        //            customer.cCusDefine10 = model.DEF10;
        //            customer.cCusDefine11 = model.DEF11.ObjToInt32();
        //            customer.cCusDefine12 = model.DEF12.ObjToInt32();
        //            customer.cCusDefine13 = model.DEF13.ObjToDecimal();
        //            customer.cCusDefine14 = model.DEF14.ObjToDecimal();
        //            customer.cCusDefine15 = model.DEF15.ObjToDateTimeNull();
        //            customer.cCusDefine16 = model.DEF16.ObjToDateTimeNull();

        //            cmd = UFIDA.U8.DB.DAL.Customer.GetUpdCommand(customer);
        //        }
        //        return cmd;
        //    }
        //    catch (Exception ex)
        //    {
        //        U8.PUB.LogHelper.WriteLine(ex.ToString());
        //        throw ex;
        //    }
        //}


        //        private bool syncVendorData(DataRowCollection ds)
        //        {
        //            try
        //            {
        //                List<Vendor> meslist = new List<Vendor>();

        //                UFIDA.U8.DB.CommandInfo cmd;
        //                UFIDA.NC.DB.Model.BD_SUPPLIER model = null;
        //                //同步
        //                foreach (DataRow dr in ds)
        //                {
        //                    if (dr["ischeck"].ObjToInt32() == 0)
        //                    {
        //                        continue;   
        //                    }

        //                    try
        //                    {
        //                        List<UFIDA.U8.DB.CommandInfo> sqllist = new List<UFIDA.U8.DB.CommandInfo>();

        //                        string cvencode = dr["PK_supplier"].ToString();
        //                        model = UFIDA.NC.DB.DAL.BD_SUPPLIER.GetModel(cvencode, corp, NcConnectstring);

        //                        if (model != null)
        //                        {
        //                            if (UFIDA.U8.DB.DAL.Vendor.Exists(model.CODE, tragetconnectstring))
        //                            {
        //                                cmd = this.getVendorUpdcmd(model);
        //                            }
        //                            else
        //                            {
        //                                cmd = this.getVendorAddcmd(model);
        //                            }

        //                            if (cmd != null)
        //                            {
        //                                sqllist.Add(cmd);
        //                            }

        //                            Vendor mes = new Vendor();
        //                            mes.VendorCode = model.CODE;
        //                            mes.VendorName = model.NAME;
        //                            mes.VendorCCode = model.SUPPLIERCLASS.CODE;
        //                            mes.StartFlag = 1;
        //                            mes.OmFlag = 0;

        //                            mes.ShortName = model.NAME; //供应商简称-plf
        //                            meslist.Add(mes);


        //                            //联系人
        //                            if (model.SUPLINKMANList != null && model.SUPLINKMANList.Count > 0)
        //                            {
        //                                //先删除
        //                                sqllist.Add(UFIDA.U8.DB.DAL.Ven_Contact.DeleteList(model.CODE));
        //                                //再增加
        //                                foreach (UFIDA.NC.DB.Model.BD_SUPLINKMAN linkman in model.SUPLINKMANList)
        //                                {    
        //                                    sqllist.Add(this.getVen_ContactrAdd(linkman, model.CODE, tragetconnectstring));   
        //                                }
        //                            }

        //                            //银行信息
        //                            if (model.CUSTBANKList != null && model.CUSTBANKList.Count > 0)
        //                            {
        //                                //先删除
        //                                sqllist.Add(UFIDA.U8.DB.DAL.VendorBank.GetDeleteList(model.CODE));
        //                                //再增加
        //                                foreach (UFIDA.NC.DB.Model.BD_CUSTBANK bank in model.CUSTBANKList)
        //                                { 
        //                                    sqllist.Add(this.getVenBankAdd(bank, model.CODE));    
        //                                }
        //                            }

        //                            if (sqllist.Count > 0)
        //                            {
        //                                DbHelperSQL.ExecuteSqlTran(sqllist, tragetconnectstring);
        //                                LogHelper.WriteLine("完成：供应商档案" + model.CODE);
        //                                //MessageBox.Show("程序执行结束"); //，可以查询U8SOFT\\Logs\\目录下日志，是否有错误信息
        //                            }   
        //                        }
        //                    }
        //                    catch (Exception ex)
        //                    {
        //                        LogHelper.WriteLine("下载错误：供应商档案=" + model.CODE + " Err Info:"+ ex.Message);
        //                        continue;
        //                    }      
        //                }


        //                try
        //                {
        //                    //传MES
        //                    if (meslist != null && meslist.Count > 0)
        //                    {

        //                        ApiRequest req = new ApiRequest();
        //                        req.data = meslist;
        //                        req.orgcode = accid;
        //                        req.primarykey = Guid.NewGuid().ToString();
        //                        req.operation = 0;
        //                        LogHelper.WriteLine("供应商档案", "GetCustJs", req.ToJson());

        //                        var result = HttpHelper.PostDataToServer(url + venurl, req.ToJson());
        //                        var apiresult = Common.DeserializeObject<ApiResponse>(result);
        //                        if (apiresult.successful != 0)
        //                        {
        //                            LogHelper.WriteLine("ERROR：供应商档案传MES" + apiresult.message);
        //                            //throw new Exception(apiresult.message);
        //                        }
        //                    }
        //                }
        //                catch (Exception e)
        //                {
        //                    LogHelper.WriteLine("传递MES供应商失败" + e.Message);
        //                }

        //                return true;
        //            }
        //            catch (Exception ex)
        //            {
        //                LogHelper.WriteLine(ex.ToString());
        //                throw ex;
        //            }
        //        }

        //        private CommandInfo getVendorUpdcmd(NC.DB.Model.BD_SUPPLIER supplier)
        //        {
        //            CommandInfo cmd = null;
        //            try
        //            {
        //                UFIDA.U8.DB.Model.Vendor model = UFIDA.U8.DB.DAL.Vendor.GetModel(supplier.CODE, tragetconnectstring);
        //                if (model != null)
        //                {
        //                    model.cVenName = supplier.NAME;
        //                    model.cVenAbbName = supplier.NAME;

        //                    model.cVenRegCode = supplier.TAXPAYERID;
        //                    model.cVenLPerson = supplier.LEGALBODY;

        //                    model.cVCCode = supplier.SUPPLIERCLASS.CODE;

        //                    //税率
        //                    model.iVenTaxRate = supplier.itaxrate;

        //                    //币种
        //                    if (supplier.CURRTYPE != null)
        //                    {
        //                        model.cVenExch_name = supplier.CURRTYPE.NAME;
        //                    }
        //                    //地址
        //                    if (supplier.ADDRESS != null)
        //                    {
        //                        model.cVenAddress = supplier.ADDRESS.DETAILINFO;
        //                    }

        //                    //联系人
        //                    if (supplier.SUPLINKMANList != null && supplier.SUPLINKMANList.Count > 0)
        //                    {
        //                        model.cVenPerson = supplier.SUPLINKMANList[0].LINKMAN.NAME;
        //                        model.cVenPhone = supplier.SUPLINKMANList[0].LINKMAN.PHONE;
        //                        model.cVenFax = supplier.SUPLINKMANList[0].LINKMAN.FAX;
        //                        model.cVenHand = supplier.SUPLINKMANList[0].LINKMAN.PHONE;
        //                        model.cVenEmail = supplier.SUPLINKMANList[0].LINKMAN.EMAIL;
        //                    }

        //                    //专管部门 业务员
        //                    if (supplier.SUPFINANCE != null)
        //                    {
        //                        if (!string.IsNullOrEmpty(supplier.SUPFINANCE.respdeptcode))
        //                        {
        //                            model.cVenDepart = supplier.SUPFINANCE.respdeptcode;
        //                        }
        //                        if (!string.IsNullOrEmpty(supplier.SUPFINANCE.resppsncode))
        //                        {
        //                            model.cVenPPerson = supplier.SUPFINANCE.resppsncode;
        //                        }
        //                        //付款协议
        //                        if (supplier.SUPFINANCE.PAYMENT != null)
        //                        {
        //                            model.cVenPUOMProtocol = supplier.SUPFINANCE.PAYMENT.CODE;
        //                        }
        //                        //结算方式
        //                        if (supplier.SUPFINANCE.DEF1 != null)
        //                        {
        //                            model.cVenSSCode = supplier.SUPFINANCE.DEF1;
        //                        }
        //                    }

        //                    //银行信息
        //                    if (supplier.CUSTBANKList != null && supplier.CUSTBANKList.Count > 0)
        //                    {
        //                        model.cVenBank = supplier.CUSTBANKList[0].BANKACCBAS.BANKDOC.NAME;
        //                        //model.cVenBankCode = supplier.CUSTBANKList[0].BANKACCBAS.BANKDOC.CODE;
        //                        model.cVenAccount = supplier.CUSTBANKList[0].BANKACCBAS.ACCNUM;
        //                        model.cVenDefine3 = supplier.CUSTBANKList[0].BANKACCBAS.BANKDOC.SWIFTCODE;
        //                    }


        //                    //model.cVenDefine1 = supplier.DEF1;
        //                    //model.cVenDefine2 = supplier.DEF2;
        //                    //model.cVenDefine3 = supplier.DEF3;
        //                    model.cVenDefine4 = this.GetNCDefName(supplier.DEF1, NcConnectstring);
        //                    model.cVenDefine5 = supplier.DEF2;
        //                    model.cVenDefine6 = supplier.DEF3;
        //                    model.cVenDefine7 = supplier.DEF7;
        //                    model.cVenDefine8 = this.GetNCDefName(supplier.DEF4, NcConnectstring);
        //                    model.cVenDefine9 = supplier.DEF9;
        //                    model.cVenDefine10 = supplier.DEF10;
        //                    model.cVenDefine11 = supplier.DEF11.ObjToInt32();
        //                    model.cVenDefine12 = supplier.DEF12.ObjToInt32();
        //                    model.cVenDefine13 = supplier.DEF13.ObjToDecimal();
        //                    model.cVenDefine14 = supplier.DEF14.ObjToDecimal();
        //                    model.cVenDefine15 = supplier.DEF15.ObjToDateTimeNull();
        //                    model.cVenDefine16 = supplier.DEF16.ObjToDateTimeNull();
        //                    model.cMemo = supplier.MEMO;


        //                    cmd = UFIDA.U8.DB.DAL.Vendor.GetUpdCommand(model);
        //                }
        //                return cmd;
        //            }
        //            catch (Exception ex)
        //            {
        //                U8.PUB.LogHelper.WriteLine(ex.ToString());
        //                throw ex;
        //            }
        //        }

        //        private string GetNCDefName(string PK_DEFDOC, string connstr)
        //        {
        //            UFIDA.NC.DB.Model.BD_DEFDOC def = UFIDA.NC.DB.DAL.BD_DEFDOC.GetModel(PK_DEFDOC, connstr);
        //            if (def == null)
        //            {
        //                return "";                
        //            }

        //            return def.NAME;
        //        }

        //        private CommandInfo getVendorAddcmd(NC.DB.Model.BD_SUPPLIER supplier)
        //        {
        //            CommandInfo cmd = null;
        //            try
        //            {
        //                UFIDA.U8.DB.Model.Vendor model = new DB.Model.Vendor();
        //                model.cVenCode = supplier.CODE;
        //                model.cVenName = supplier.NAME;
        //                model.cVenAbbName = supplier.NAME;

        //                model.cVenRegCode = supplier.TAXPAYERID;
        //                model.cVenLPerson = supplier.LEGALBODY;
        ////                model.cVenEmail = supplier.EMAIL;
        //                model.cVCCode = supplier.SUPPLIERCLASS.CODE;
        //                //税率
        //                model.iVenTaxRate = supplier.itaxrate;
        //                //发展日期
        //                model.dVenDevDate = DateTime.Now.Date;
        //                //币种
        //                if (supplier.CURRTYPE != null)
        //                {
        //                    model.cVenExch_name = supplier.CURRTYPE.NAME;    
        //                }                  

        //                //地址
        //                if (supplier.ADDRESS != null)
        //                {
        //                    model.cVenAddress = supplier.ADDRESS.DETAILINFO;
        //                }

        //                //联系人
        //                if (supplier.SUPLINKMANList != null && supplier.SUPLINKMANList.Count > 0)
        //                {
        //                    model.cVenPerson = supplier.SUPLINKMANList[0].LINKMAN.NAME;
        //                    model.cVenPhone = supplier.SUPLINKMANList[0].LINKMAN.PHONE;
        //                    model.cVenFax = supplier.SUPLINKMANList[0].LINKMAN.FAX;
        //                    model.cVenHand = supplier.SUPLINKMANList[0].LINKMAN.PHONE;
        //                    model.cVenEmail = supplier.SUPLINKMANList[0].LINKMAN.EMAIL;
        //                }


        //                if (supplier.SUPFINANCE != null)
        //                {
        //                    //专管部门 业务员
        //                    if (!string.IsNullOrEmpty(supplier.SUPFINANCE.respdeptcode))
        //                    {
        //                        model.cVenDepart = supplier.SUPFINANCE.respdeptcode;
        //                    }
        //                    if (!string.IsNullOrEmpty(supplier.SUPFINANCE.resppsncode))
        //                    {
        //                        model.cVenPPerson = supplier.SUPFINANCE.resppsncode;
        //                    }
        //                    //付款协议
        //                    if (supplier.SUPFINANCE.PAYMENT != null)
        //                    {
        //                        model.cVenPUOMProtocol = supplier.SUPFINANCE.PAYMENT.CODE;                        
        //                    }
        //                    //结算方式
        //                    if (supplier.SUPFINANCE.DEF1 != null)
        //                    {
        //                        model.cVenSSCode = supplier.SUPFINANCE.DEF1;
        //                    }

        //                }

        //                //银行信息
        //                if (supplier.CUSTBANKList != null && supplier.CUSTBANKList.Count > 0)
        //                {
        //                    model.cVenBank = supplier.CUSTBANKList[0].BANKACCBAS.BANKDOC.NAME;
        //                    //model.cVenBankCode = supplier.CUSTBANKList[0].BANKACCBAS.BANKDOC.CODE;
        //                    model.cVenAccount = supplier.CUSTBANKList[0].BANKACCBAS.ACCNUM;
        //                    model.cVenDefine3 = supplier.CUSTBANKList[0].BANKACCBAS.BANKDOC.SWIFTCODE;
        //                }


        //                //model.cVenDefine1 = supplier.DEF1;
        //                //model.cVenDefine2 = supplier.DEF2;
        //                //model.cVenDefine3 = supplier.DEF3;
        //                model.cVenDefine4 = this.GetNCDefName(supplier.DEF1, NcConnectstring);
        //                model.cVenDefine5 = supplier.DEF2;
        //                model.cVenDefine6 = supplier.DEF3;
        //                model.cVenDefine7 = supplier.DEF7;
        //                model.cVenDefine8 = this.GetNCDefName(supplier.DEF4, NcConnectstring);
        //                model.cVenDefine9 = supplier.DEF9;
        //                model.cVenDefine10 = supplier.DEF10;
        //                model.cVenDefine11 = supplier.DEF11.ObjToInt32();
        //                model.cVenDefine12 = supplier.DEF12.ObjToInt32();
        //                model.cVenDefine13 = supplier.DEF13.ObjToDecimal();
        //                model.cVenDefine14 = supplier.DEF14.ObjToDecimal();
        //                model.cVenDefine15 = supplier.DEF15.ObjToDateTimeNull();
        //                model.cVenDefine16 = supplier.DEF16.ObjToDateTimeNull();
        //                model.cMemo = supplier.MEMO;

        //                cmd = UFIDA.U8.DB.DAL.Vendor.GetAddCommand(model);

        //                return cmd;         
        //            }
        //            catch (Exception ex)
        //            {
        //                U8.PUB.LogHelper.WriteLine(ex.ToString());
        //                throw ex;
        //            }
        //        }

        //        private CommandInfo getVenBankAdd(NC.DB.Model.BD_CUSTBANK bank, string cVencode)
        //        {
        //            CommandInfo cmd = null;
        //            try
        //            {
        //                UFIDA.U8.DB.Model.VendorBank cbank = new DB.Model.VendorBank();

        //                cbank.cVenCode = cVencode;
        //                cbank.cAccountNum = bank.BANKACCBAS.ACCNUM;
        //                cbank.cAccountName = bank.BANKACCBAS.ACCNAME;
        //                cbank.cBranch = bank.BANKACCBAS.BANKDOC.NAME;
        //                //cbank.cBank = bank.BANKACCBAS.BANKDOC.CODE;
        //                cbank.bDefault = false;

        //                cmd = UFIDA.U8.DB.DAL.VendorBank.GetAddCommand(cbank);  
        //                return cmd;
        //            }
        //            catch (Exception ex)
        //            {
        //                U8.PUB.LogHelper.WriteLine(ex.ToString());
        //                throw ex;
        //            }
        //        }

        //        private CommandInfo getVenBankUpd(NC.DB.Model.BD_CUSTBANK bank, string cVencode)
        //        {
        //            CommandInfo cmd = null;
        //            try
        //            {
        //                UFIDA.U8.DB.Model.VendorBank cbank = UFIDA.U8.DB.DAL.VendorBank.GetModel(cVencode, bank.BANKACCBAS.ACCNUM, tragetconnectstring);
        //                if (cbank != null)
        //                {
        //                    cbank.cAccountName = bank.BANKACCBAS.ACCNAME;
        //                    cbank.cBranch = bank.BANKACCBAS.BANKDOC.NAME;
        //                    cbank.cBank = bank.BANKACCBAS.BANKDOC.CODE;

        //                    cmd = UFIDA.U8.DB.DAL.VendorBank.GetUpdCommand(cbank);
        //                }
        //                return cmd;
        //            }
        //            catch (Exception ex)
        //            {
        //                U8.PUB.LogHelper.WriteLine(ex.ToString());
        //                throw ex;
        //            }
        //        }

        //        private CommandInfo getVen_ContactrAdd(NC.DB.Model.BD_SUPLINKMAN linkman, string cVenCode, string tragetconnectstring)
        //        {
        //            CommandInfo cmd = null;
        //            try
        //            {
        //                UFIDA.U8.DB.Model.Ven_Contact model = new DB.Model.Ven_Contact();
        //                model.cVenCode = cVenCode;
        //                model.cContactCode = linkman.LINKMAN.PK_LINKMAN;
        //                model.cContactName = linkman.LINKMAN.NAME;
        //                model.cMobilePhone = linkman.LINKMAN.PHONE;
        //                model.cMemo = linkman.LINKMAN.MEMO;
        //                model.cEmail = linkman.LINKMAN.EMAIL;
        //                model.cOfficePhone = linkman.LINKMAN.PHONE;
        //                model.OID = "{" + Guid.NewGuid().ToString() + "}";
        //                model.cCreator = "NC";
        //                model.dCreateDate = DateTime.Now;       

        //                cmd = UFIDA.U8.DB.DAL.Ven_Contact.GetAddCommand(model);    
        //                return cmd;
        //            }
        //            catch (Exception ex)
        //            {
        //                U8.PUB.LogHelper.WriteLine(ex.ToString());
        //                throw ex;
        //            }
        //        }

        //        private CommandInfo getVen_ContactrUpd(NC.DB.Model.BD_SUPLINKMAN linkman, string cVenCode, string tragetconnectstring)
        //        {
        //            CommandInfo cmd = null;
        //            try
        //            {
        //                UFIDA.U8.DB.Model.Ven_Contact model = UFIDA.U8.DB.DAL.Ven_Contact.GetModel(cVenCode, linkman.LINKMAN.CODE, tragetconnectstring);
        //                if (model != null)
        //                {
        //                    model.cContactName = linkman.LINKMAN.NAME;
        //                    model.cMobilePhone = linkman.LINKMAN.PHONE;
        //                    model.cMemo = linkman.LINKMAN.MEMO;
        //                    model.cEmail = linkman.LINKMAN.EMAIL;
        //                    model.cOfficePhone = linkman.LINKMAN.PHONE;
        //                    model.dModifyDate = DateTime.Now;

        //                    cmd = UFIDA.U8.DB.DAL.Ven_Contact.GetUpdCommand(model);
        //                }
        //                return cmd;
        //            }
        //            catch (Exception ex)
        //            {
        //                U8.PUB.LogHelper.WriteLine(ex.ToString());
        //                throw ex;
        //            }
        //        }

        //private void ResetHeaderCheckBoxLocation(int ColumnIndex, int RowIndex)
        //{
        //    Rectangle oRectangle = this.dgvrl.GetCellDisplayRectangle(ColumnIndex, RowIndex, true);            
        //    Point oPoint = new Point();            
        //    oPoint.X = oRectangle.Location.X + (oRectangle.Width - HeaderCheckBox.Width) / 2 + 1;            
        //    oPoint.Y = oRectangle.Location.Y + (oRectangle.Height - HeaderCheckBox.Height) / 2 + 1;            
        //    HeaderCheckBox.Location = oPoint;
        //}

        //private void syncProuting(string tragetconnectstring)
        //{
        //    dsoperation.AcceptChanges();
        //    try
        //    {
        //        if (dgvprouting.RowCount > 0)
        //        {
        //            DataRow[] rows = dsoperation.Tables[0].Select("ischeck=1");

        //            if (rows != null && rows.Length > 0)
        //            {
        //                //标准工序同步 
        //                int icount = 0;
        //                //同步
        //                foreach (DataRow dr in rows)
        //                {
        //                    int PRoutingId = Convert.ToInt32(dr["PRoutingId"].ToString());
        //                    this.syncProutingData(PRoutingId, "", tragetconnectstring, ref icount);
        //                }

        //                MessageBox.Show("程序执行结束, 共插入" + icount + "条工艺路线数据"); //，可以查询U8SOFT\\Logs\\目录下日志，是否有错误信息 

        //            }
        //            else
        //            {
        //                MessageBox.Show("请先选择明细信息");
        //            }

        //        }
        //        else
        //        {
        //            MessageBox.Show("明细信息空");
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        throw e;
        //    }
        //}


        //private void syncBom(string tragetconnectstring)
        //{
        //    dsbom.AcceptChanges();
        //    try
        //    {
        //        if (dgvbom.RowCount > 0)
        //        {
        //            DataRow[] rows = dsbom.Tables[0].Select("ischeck=1");

        //            if (rows != null && rows.Length > 0)
        //            {

        //                int icount = 0;
        //                //同步
        //                foreach (DataRow dr in rows)
        //                {
        //                    int bomid = Convert.ToInt32(dr["bomid"].ToString());
        //                    this.syncBomData(bomid, "", tragetconnectstring, ref icount);

        //                }
        //                MessageBox.Show("程序执行结束, 插入" + icount + "条BOM数据"); //，可以查询U8SOFT\\Logs\\目录下日志，是否有错误信息

        //            }
        //            else
        //            {
        //                MessageBox.Show("请先选择明细信息");
        //            }

        //        }
        //        else
        //        {
        //            MessageBox.Show("明细信息空");
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        throw e;
        //    }
        //}


        //private bool syncCustomerData(DataRowCollection ds)
        //{
        //    try
        //    {
        //        List<Customer> meslist = new List<Customer>();

        //        UFIDA.U8.DB.CommandInfo cmd;
        //        UFIDA.NC.DB.Model.BD_CUSTOMER model;
        //        //同步
        //        foreach (DataRow dr in ds)
        //        {
        //            if (dr["ischeck"].ObjToInt32() == 0)
        //            {
        //                continue;
        //            }
        //            List<UFIDA.U8.DB.CommandInfo> sqllist = new List<UFIDA.U8.DB.CommandInfo>();
        //            string ccuscode = dr["pk_customer"].ToString();
        //            model = UFIDA.NC.DB.DAL.BD_CUSTOMER.GetModel(ccuscode, NcConnectstring);
        //            try
        //            {
        //                if (model != null)
        //                {
        //                    if (UFIDA.U8.DB.DAL.Customer.Exists(model.CODE, tragetconnectstring))
        //                    {
        //                        cmd = this.getCustomerUpdcmd(model); //UFIDA.U8.DB.DAL.Customer.GetUpdCommand(model);
        //                    }
        //                    else
        //                    {
        //                        cmd = this.getCustomerInscmd(model); // UFIDA.U8.DB.DAL.Customer.GetAddCommand(model);
        //                    }

        //                    if (cmd != null)
        //                    {
        //                        sqllist.Add(cmd);
        //                    }

        //                    Customer mes = new Customer();

        //                    mes.CustomerCCode = model.CUSTCLASS.CODE;
        //                    mes.CustomerName = model.NAME;
        //                    mes.ShortName = model.NAME;
        //                    mes.StartFlag = 1;
        //                    mes.CustomerCode = model.CODE;

        //                    mes.Reserved5 = 0;
        //                    meslist.Add(mes);

        //                    //客户地址
        //                    if (model.CUSTADDRESSList != null && model.CUSTADDRESSList.Count > 0)
        //                    {
        //                        //先删除
        //                        sqllist.Add(UFIDA.U8.DB.DAL.CusDeliverAdd.GetDelList(model.CODE));
        //                        //再增加
        //                        foreach (UFIDA.NC.DB.Model.BD_CUSTADDRESS deliver in model.CUSTADDRESSList)
        //                        {
        //                            sqllist.Add(this.getCusDeliverAdd(deliver, model.CODE, tragetconnectstring));
        //                        }
        //                    }

        //                    //客户联系人
        //                    if (model.CUSTLINKMANList != null && model.CUSTLINKMANList.Count > 0)
        //                    {
        //                        //先删除
        //                        sqllist.Add(UFIDA.U8.DB.DAL.Crm_Contact.GetDeleteList(model.CODE));
        //                        //再增加
        //                        foreach (UFIDA.NC.DB.Model.BD_CUSTLINKMAN linkman in model.CUSTLINKMANList)
        //                        {
        //                            sqllist.Add(this.getCrm_ContactrAdd(linkman, model.CODE, tragetconnectstring));
        //                        }
        //                    }

        //                    //客户银行信息
        //                    if (model.CUSTBANKList != null && model.CUSTBANKList.Count > 0)
        //                    {
        //                        //先删除
        //                        sqllist.Add(UFIDA.U8.DB.DAL.CustomerBank.GetDeleteList(model.CODE));
        //                        //再增加
        //                        foreach (UFIDA.NC.DB.Model.BD_CUSTBANK bank in model.CUSTBANKList)
        //                        {
        //                            sqllist.Add(this.getcustBankAdd(bank, model.CODE));
        //                        }
        //                    }

        //                    if (sqllist.Count > 0)
        //                    {
        //                        DbHelperSQL.ExecuteSqlTran(sqllist, tragetconnectstring);
        //                        LogHelper.WriteLine("完成：客户档案" + model.CODE);
        //                        //MessageBox.Show("程序执行结束"); //，可以查询U8SOFT\\Logs\\目录下日志，是否有错误信息
        //                    }
        //                }
        //            }
        //            catch (Exception ex)
        //            {
        //                LogHelper.WriteLine("下载错误：客户档案=" + model.CODE + " Err Info:" + ex.Message);
        //                continue;
        //            }
        //        }

        //        try
        //        {
        //            //传MES
        //            if (meslist != null && meslist.Count > 0)
        //            {
        //                ApiRequest req = new ApiRequest();
        //                req.data = meslist;
        //                req.orgcode = accid;
        //                req.primarykey = Guid.NewGuid().ToString();
        //                req.operation = 0;
        //                LogHelper.WriteLine("客户档案", "GetCustJs", req.ToJson());

        //                var result = HttpHelper.PostDataToServer(url + cusurl, req.ToJson());
        //                var apiresult = Common.DeserializeObject<ApiResponse>(result);
        //                if (apiresult.successful != 0)
        //                {
        //                    LogHelper.WriteLine("ERROR：客户档案传MES" + apiresult.message);
        //                    //throw new Exception(apiresult.message);
        //                }
        //            }
        //        }
        //        catch (Exception e)
        //        {
        //            LogHelper.WriteLine("传递MES客户失败：" + e.Message);
        //        }

        //        return true;
        //    }
        //    catch (Exception ex)
        //    {
        //        LogHelper.WriteLine(ex.ToString());
        //        throw ex;
        //    }
        //}

        /// <summary>
        /// prouting 产品工艺路线同步
        /// </summary>
        /// <param name="PRoutingId">工艺路线id</param>
        /// <param name="u8connectstring">u8帐套库连接串</param>
        /// <param name="tragetconnect">目标帐套连接串</param>
        /// <param name="icount"></param>
        //private void syncProutingData(int PRoutingId, string u8connectstring, string tragetconnect, ref int icount)
        //{
        //    try
        //    {
        //        List<UFIDA.U8.DB.CommandInfo> sqllist = new List<UFIDA.U8.DB.CommandInfo>();
        //        List<UFIDA.U8.DB.CommandInfo> cmd = new List<CommandInfo>();
        //        UFIDA.U8.DB.Model.sfc_prouting model;

        //        model = UFIDA.U8.DB.DAL.sfc_prouting.GetModel(PRoutingId, u8connectstring);

        //        if (UFIDA.U8.DB.DAL.sfc_prouting.Exists(PRoutingId, tragetconnect))
        //        {
        //            cmd = UFIDA.U8.DB.DAL.sfc_prouting.GetDelCommand(model);
        //            if (cmd.Count > 0)
        //            {
        //                DbHelperSQL.ExecuteSqlTran(cmd, tragetconnect);
        //            }
        //        }

        //        cmd = UFIDA.U8.DB.DAL.sfc_prouting.GetAddCommand(model);

        //        sqllist = cmd;

        //        if (sqllist.Count > 0)
        //        {
        //            icount += 1;
        //            DbHelperSQL.ExecuteSqlTran(sqllist, tragetconnect);
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        throw e;
        //    }
        //}


        //private DataTable getproutingbyinv(string cinvcode, string connectstring)
        //{
        //    string sql = "select PRoutingId from sfc_proutingpart a inner join bas_part b on b.PartId = a.PartId where b.invcode = '" + cinvcode + "'";
        //    try
        //    {
        //        DataTable dt = DbHelperSQL.QueryAsDT(sql, connectstring);
        //        return dt;
        //    }
        //    catch (Exception e)
        //    {
        //        throw e;
        //    }

        //}

        //private DataTable getbombyinv(string cinvcode, string connectstring)
        //{
        //    string sql = "select a.BomId from bom_parent a inner join bas_part b on b.PartId = a.ParentId where b.InvCode = '" + cinvcode + "'";
        //    try
        //    {
        //        DataTable dt = DbHelperSQL.QueryAsDT(sql, connectstring);
        //        return dt;
        //    }
        //    catch (Exception e)
        //    {
        //        throw e;
        //    }
        //}


        /// <summary>
        /// 查询工艺路线
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void buttonX4_Click(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        dsoperation = this.queryData4();
        //        bdsoperation.DataSource = dsoperation;
        //        bdsoperation.DataMember = "prouting";
        //        ocount.Text = bdsoperation.Count.ToString();
        //    }
        //    catch (Exception ex)
        //    {
        //        U8.PUB.LogHelper.WriteLine(this.GetType() + ":" + ex.Message);
        //        MessageBox.Show(ex.Message);
        //    }
        //}

        /// <summary>
        /// 查询物料清单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void buttonX5_Click(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        dsbom = this.queryData5();
        //        bdsbom.DataSource = dsbom;
        //        bdsbom.DataMember = "bom";
        //        bcount.Text = bdsbom.Count.ToString();
        //    }
        //    catch (Exception ex)
        //    {
        //        U8.PUB.LogHelper.WriteLine(this.GetType() + ":" + ex.Message);
        //        MessageBox.Show(ex.Message);
        //    }
        //}


        //private string getCustomersql(string corp)
        //{
        //    StringBuilder sql = new StringBuilder();


        //    sql.AppendLine(" pk_customer in ( select pk_customer from bd_custorg where pk_org in ( '" + corp + "' ) and enablestate = 2  union select pk_customer from bd_customer where  pk_org = '" + corp + "'  )  ");

        //    //客户编码
        //    if (!string.IsNullOrEmpty(edtccuscode.Text))
        //    {
        //        sql.Append(" and code like '%" + edtccuscode.Text.ToString() + "%'");
        //    }
        //    //客户名称
        //    if (!string.IsNullOrEmpty(edtccusname.Text))
        //    {
        //        sql.Append(" and name like '%" + edtccusname.Text.ToString() + "%'");
        //    }
        //    //创建日期
        //    if (!string.IsNullOrEmpty(dtCusAddDate1.Text))
        //    {
        //        sql.Append(" and creationtime >= '" + dtCusAddDate1.Text.ToString() + "'");
        //    }
        //    if (!string.IsNullOrEmpty(dtCusAddDate2.Text))
        //    {
        //        sql.Append(" and creationtime <= '" + dtCusAddDate2.Text.ToString() + "'");
        //    }
        //    //修改日期
        //    if (!string.IsNullOrEmpty(dtCusModifyDate1.Text))
        //    {
        //        sql.Append(" and modifiedtime >= '" + dtCusModifyDate1.Text.ToString() + "'");
        //    }
        //    if (!string.IsNullOrEmpty(dtCusModifyDate2.Text))
        //    {
        //        sql.Append(" and modifiedtime <= '" + dtCusModifyDate2.Text.ToString() + "'");
        //    }


        //    return sql.ToString();
        //}


        //private DataSet queryData4()
        //{
        //    //工艺路线数据
        //    StringBuilder sql = new StringBuilder();
        //    sql.Append("select 0 as ischeck, t.PRoutingId, a.cinvcode, a.cinvname, a.cinvstd, b.ccomunitname, t.version, t.versiondesc, t.versioneffdate from inventory a inner join computationunit b on b.ccomunitcode = a.ccomunitcode ");
        //    sql.AppendLine(" inner join bas_part p on p.invcode = a.cinvcode ");
        //    sql.AppendLine(" inner join sfc_proutingpart  pp on pp.partid = p.partid ");
        //    sql.AppendLine(" inner join sfc_prouting t on t.PRoutingId = pp.PRoutingId  ");
        //    sql.AppendLine(" where 1=1 ");

        //    if (!string.IsNullOrEmpty(edtcinvcode1.Text))
        //    {
        //        sql.AppendLine(" and a.cinvcode like '%" + edtcinvcode1.Text + "%'");
        //    }
        //    if (!string.IsNullOrEmpty(edtcinvname1.Text))
        //    {
        //        sql.AppendLine(" and a.cinvname like '%" + edtcinvname1.Text + "%'");
        //    }
        //    if (!string.IsNullOrEmpty(dateTimeInput16.Text))
        //    {
        //        sql.AppendLine(" and t.CreateDate >= '" + dateTimeInput16.Text + "'");
        //    }
        //    if (!string.IsNullOrEmpty(dateTimeInput15.Text))
        //    {
        //        sql.AppendLine(" and t.CreateDate <= '" + dateTimeInput15.Text + "'");
        //    }
        //    if (!string.IsNullOrEmpty(dateTimeInput14.Text))
        //    {
        //        sql.AppendLine(" and t.ModifyDate >= '" + dateTimeInput14.Text + "'");
        //    }
        //    if (!string.IsNullOrEmpty(dateTimeInput13.Text))
        //    {
        //        sql.AppendLine(" and t.ModifyDate <= '" + dateTimeInput13.Text + "'");
        //    }
        //    try
        //    {
        //        return DbHelperSQL.Query(sql.ToString(), "prouting", "");
        //    }
        //    catch (Exception e)
        //    {
        //        U8.PUB.LogHelper.WriteLine("queryData:" + e.Message);
        //        throw e;
        //    }
        //}

        //private DataSet queryData5()
        //{
        //    //物料清单数据
        //    StringBuilder sql = new StringBuilder();
        //    sql.Append("select 0 as ischeck, t.bomid, a.cinvcode, a.cinvname, a.cinvstd, b.ccomunitname, t.version, t.versiondesc, t.versioneffdate from inventory a inner join computationunit b on b.ccomunitcode = a.ccomunitcode ");
        //    sql.AppendLine(" inner join bas_part p on p.invcode = a.cinvcode ");
        //    sql.AppendLine(" inner join bom_parent  pp on pp.parentid = p.partid ");
        //    sql.AppendLine(" inner join bom_bom t on t.bomid = pp.bomid ");
        //    sql.AppendLine(" where 1=1 ");

        //    if (!string.IsNullOrEmpty(edtcinvcode2.Text))
        //    {
        //        sql.AppendLine(" and a.cinvcode like '%" + edtcinvcode2.Text + "%'");
        //    }
        //    if (!string.IsNullOrEmpty(edtcinvname2.Text))
        //    {
        //        sql.AppendLine(" and a.cinvname like '%" + edtcinvname2.Text + "%'");
        //    }
        //    if (!string.IsNullOrEmpty(dateTimeInput20.Text))
        //    {
        //        sql.AppendLine(" and t.CreateDate >= '" + dateTimeInput20.Text + "'");
        //    }
        //    if (!string.IsNullOrEmpty(dateTimeInput19.Text))
        //    {
        //        sql.AppendLine(" and t.CreateDate <= '" + dateTimeInput19.Text + "'");
        //    }
        //    if (!string.IsNullOrEmpty(dateTimeInput18.Text))
        //    {
        //        sql.AppendLine(" and t.ModifyDate >= '" + dateTimeInput18.Text + "'");
        //    }
        //    if (!string.IsNullOrEmpty(dateTimeInput17.Text))
        //    {
        //        sql.AppendLine(" and t.ModifyDate <= '" + dateTimeInput17.Text + "'");
        //    }
        //    try
        //    {
        //        return DbHelperSQL.Query(sql.ToString(), "bom", "");
        //    }
        //    catch (Exception e)
        //    {
        //        U8.PUB.LogHelper.WriteLine("queryData:" + e.Message);
        //        throw e;
        //    }
        //}


        //private DataSet queryData2()
        //{
        //    //供应商数据
        //    StringBuilder sql = new StringBuilder();
        //    sql.Append("select 0 as ischeck, a.cvencode, a.cvenname, a.dvencreatedatetime  from vendor a where 1=1 ");
        //    if (!string.IsNullOrEmpty(edtcvencode.Text))
        //    {
        //        sql.AppendLine(" and a.cvencode like '%" + edtcvencode.Text + "%'");
        //    }
        //    if (!string.IsNullOrEmpty(edtcvenname.Text))
        //    {
        //        sql.AppendLine(" and a.cvenname like '%" + edtcvenname.Text + "%'");
        //    }
        //    if (!string.IsNullOrEmpty(dtSupAddDate1.Text))
        //    {
        //        sql.AppendLine(" and a.dvencreatedatetime >= '" + dtSupAddDate1.Text + "'");
        //    }
        //    if (!string.IsNullOrEmpty(dtSupAddDate2.Text))
        //    {
        //        sql.AppendLine(" and a.dvencreatedatetime <= '" + dtSupAddDate2.Text + "'");
        //    }
        //    if (!string.IsNullOrEmpty(dtSupModifyDate1.Text))
        //    {
        //        sql.AppendLine(" and a.dModifyDate >= '" + dtSupModifyDate1.Text + "'");
        //    }
        //    if (!string.IsNullOrEmpty(dtSupModifyDate2.Text))
        //    {
        //        sql.AppendLine(" and a.dModifyDate <= '" + dtSupModifyDate2.Text + "'");
        //    }
        //    try
        //    {
        //        return DbHelperSQL.Query(sql.ToString(), "vendor", "");
        //    }
        //    catch (Exception e)
        //    {
        //        U8.PUB.LogHelper.WriteLine("queryData:" + e.Message);
        //        throw e;
        //    }
        //}


        //private bool addQCSWB(WB wb, string contr, string errMsg)
        //{
        //    try
        //    {
        //        List<CommandInfo> cmdlist = new List<CommandInfo>();

        //        #region 组织QCS_Maintenance
        //        StringBuilder sqlMaintenance = new StringBuilder();
        //        sqlMaintenance.Append("insert into [QCS_Maintenance] (");
        //        sqlMaintenance.Append("contract_serial,order_serial,amount,sales_name,project_name,signing_customer_id,signing_customer_name,final_customer_id,final_customer_name,warranty_type,start_date,end_date,renewed_end_date,start_condition,signing_date,industry)");
        //        sqlMaintenance.Append(" values (");
        //        sqlMaintenance.Append("@contract_serial,@order_serial,@amount,@sales_name,@project_name,@signing_customer_id,@signing_customer_name,@final_customer_id,@final_customer_name,@warranty_type,@start_date,@end_date,@renewed_end_date,@start_condition,@signing_date,@industry)");
        //        SqlParameter[] parameters = {
        //            new SqlParameter("@contract_serial", SqlDbType.NVarChar,100),
        //            new SqlParameter("@order_serial", SqlDbType.NVarChar,100),
        //            new SqlParameter("@amount", SqlDbType.Decimal,9),
        //            new SqlParameter("@sales_name", SqlDbType.NVarChar,100),
        //            new SqlParameter("@project_name", SqlDbType.NVarChar,100),
        //            new SqlParameter("@signing_customer_id", SqlDbType.Int,4),
        //            new SqlParameter("@signing_customer_name", SqlDbType.NVarChar,100),
        //            new SqlParameter("@final_customer_id", SqlDbType.Int,4),
        //            new SqlParameter("@final_customer_name", SqlDbType.NVarChar,100),
        //            new SqlParameter("@warranty_type", SqlDbType.NVarChar,100),
        //            new SqlParameter("@start_date", SqlDbType.NVarChar,100),
        //            new SqlParameter("@end_date", SqlDbType.NVarChar,100),
        //            new SqlParameter("@renewed_end_date", SqlDbType.NVarChar,100),
        //            new SqlParameter("@start_condition", SqlDbType.NVarChar,100),
        //            new SqlParameter("@signing_date", SqlDbType.NVarChar,100),
        //            new SqlParameter("@industry", SqlDbType.NVarChar,100)};
        //        parameters[0].Value = wb.contract_serial;
        //        parameters[1].Value = wb.order_serial;
        //        parameters[2].Value = wb.amount == ""  0 : Convert.ToDecimal(wb.amount);
        //        parameters[3].Value = wb.sales_name;
        //        parameters[4].Value = wb.project_name;
        //        parameters[5].Value = wb.signing_customer_id;
        //        parameters[6].Value = wb.signing_customer_name;
        //        parameters[7].Value = wb.final_customer_id;
        //        parameters[8].Value = wb.final_customer_name;
        //        parameters[9].Value = wb.warranty_type;
        //        parameters[10].Value = wb.start_date;
        //        parameters[11].Value = wb.end_date;
        //        parameters[12].Value = wb.renewed_end_date;
        //        parameters[13].Value = wb.start_condition;
        //        parameters[14].Value = wb.signing_date;
        //        parameters[15].Value = wb.industry;
        //        CommandInfo cmd = new CommandInfo(sqlMaintenance.ToString(), parameters);
        //        cmdlist.Add(cmd);
        //        #endregion

        //        if (cmdlist.Count > 0)
        //        {
        //            DbHelperSQL.ExecuteSqlTran(cmdlist, contr);
        //        }
        //        return true;
        //    }
        //    catch (Exception ex)
        //    {
        //        errMsg = ex.ToString();
        //        return false;
        //    }
        //}

        //private bool delQCSWB(string serial, string contr)
        //{
        //    try
        //    {
        //        List<CommandInfo> cmdlist = new List<CommandInfo>();
        //        string sqlDetail = "delete from QCS_Maintenance where contract_serial='" + serial + "'";
        //        cmdlist.Add(new CommandInfo(sqlDetail, null));

        //        DbHelperSQL.ExecuteSqlTran(cmdlist, contr);
        //        return true;
        //    }
        //    catch
        //    {
        //        return false;
        //    }
        //}

        //private DataTable getQCSWB(string serial, string contr)
        //{
        //    string sql = "select * from QCS_Maintenance where contract_serial='" + serial + "'";
        //    DataTable dt = DbHelperSQL.QueryAsDT(sql, contr);
        //    return dt;
        //}

        //QCS订单同步存入临时表：QCS_Maintenance
        //private void syncWB(string tragetconnectstring)
        //{
        //    dsWB.AcceptChanges();
        //    try
        //    {
        //        if (dgvWB.RowCount > 0 && wbs.bodys != null)
        //        {
        //            if (wbs.bodys != null && wbs.bodys.Count > 0)
        //            {
        //                foreach (WB wb in wbs.bodys)
        //                {
        //                    //判断订单号是否在临时表中已存在，若存在就删除
        //                    DataTable dt = this.getQCSWB(wb.contract_serial, tragetconnectstring);
        //                    if (dt != null || dt.DefaultView.Count > 0)
        //                    {
        //                        bool a = this.delQCSWB(wb.contract_serial, tragetconnectstring);
        //                        if (!a)
        //                        {
        //                            MessageBox.Show("合同号" + wb.contract_serial + "删除失败");
        //                        }
        //                    }

        //                    //添加数据到临时表
        //                    string errMsg = "";
        //                    bool b = this.addQCSWB(wb, tragetconnectstring, errMsg);
        //                    if (!b)
        //                    {
        //                        MessageBox.Show("同步失败：" + errMsg);
        //                    }
        //                }
        //            }
        //        }
        //        else
        //        {
        //            MessageBox.Show("明细信息空");
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        throw e;
        //    }
        //}

        //查询QCS订单数据——2021.10.27(liny)
        //private DataSet queryData4()
        //{
        //    //获取url
        //    string url = System.Web.Configuration.WebConfigurationManager.AppSettings["qcsurl"]; // "https://qcs1.woqutech.com:4665/";

        //    //读取页面输入的参数
        //    string customer = textBoxX4.Text;//客户id
        //    string serial = textBoxX3.Text;//订单号
        //    string contract_serial = textBoxX2.Text;//合同号
        //    string final_customer = textBoxX1.Text;//最终客户id
        //    string createtime = dateTimeInput4.Text;//创建时间
        //    string updatetime = dateTimeInput2.Text;//修改时间

        //    try
        //    {
        //        //调用QCS·token接口获取token
        //        token = Common.getQCSTkoen(url);
        //        if (token == null)
        //        {
        //            MessageBox.Show("获取Token失败");
        //            return null;
        //        }

        //        //根据查询条件获取订单信息
        //        DataTable dt = new DataTable();
        //        details = Common.GetQCSDetail(url, customer, serial, contract_serial, final_customer, createtime, updatetime, token, ref dt);
        //        if (details == null)
        //        {
        //            MessageBox.Show("获取Qcs订单失败");
        //            return null;
        //        }
        //        DataSet ds = new DataSet();
        //        ds.Tables.Add(dt);
        //        return ds;

        //    }
        //    catch (Exception e)
        //    {
        //        U8.PUB.LogHelper.WriteLine("queryData:" + e.Message);
        //        throw e;
        //    }
        //}

        ////QCS订单同步存入临时表：QCS_Detail、QCS_Payment、QCS_Acceptance、QCS_Material、QCS_MaterialItem
        //private void syncDetail(string tragetconnectstring)
        //{
        //    dsdetail.AcceptChanges();
        //    try
        //    {
        //        if (dgvdetail.RowCount > 0 && details.bodys != null)
        //        {
        //            if (details.bodys != null && details.bodys.Count > 0)
        //            {
        //                foreach (detail detail in details.bodys)
        //                {
        //                    //判断订单号是否在临时表中已存在，若存在就删除
        //                    DataTable dt = this.getQCSDetail(detail.serial, tragetconnectstring);
        //                    if (dt != null || dt.DefaultView.Count > 0)
        //                    {
        //                        bool a = this.delQCSDetail(detail.serial, tragetconnectstring);
        //                        if (!a)
        //                        {
        //                            MessageBox.Show("订单号" + detail.serial + "删除失败");
        //                        }
        //                    }

        //                    //添加数据到临时表
        //                    string errMsg = "";
        //                    bool b = this.addQCSDetail(detail, tragetconnectstring, errMsg);
        //                    if (!b)
        //                    {
        //                        MessageBox.Show("同步失败：" + errMsg);
        //                    }
        //                }
        //            }
        //        }
        //        else
        //        {
        //            MessageBox.Show("明细信息空");
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        throw e;
        //    }
        //}

        //private DataTable getQCSDetail(string serial, string contr)
        //{
        //    string sql = "select * from QCS_Detail where serial='" + serial + "'";
        //    DataTable dt = DbHelperSQL.QueryAsDT(sql, contr);
        //    return dt;
        //}

        //private bool delQCSDetail(string serial, string contr)
        //{
        //    try
        //    {
        //        List<CommandInfo> cmdlist = new List<CommandInfo>();
        //        string sqlDetail = "delete from QCS_Detail where serial='" + serial + "'";
        //        cmdlist.Add(new CommandInfo(sqlDetail, null));

        //        string sqlPayment = "delete from QCS_Payment where detail_serial='" + serial + "'";
        //        cmdlist.Add(new CommandInfo(sqlPayment, null));

        //        string sqlAcceptance = "delete from QCS_Acceptance where detail_serial='" + serial + "'";
        //        cmdlist.Add(new CommandInfo(sqlAcceptance, null));

        //        string sqlMaterial = "delete from QCS_Material where detail_serial='" + serial + "'";
        //        cmdlist.Add(new CommandInfo(sqlMaterial, null));

        //        string sqlMaterialItem = "delete from QCS_MaterialItem where detail_serial='" + serial + "'";
        //        cmdlist.Add(new CommandInfo(sqlMaterialItem, null));

        //        DbHelperSQL.ExecuteSqlTran(cmdlist, contr);
        //        return true;
        //    }
        //    catch
        //    {
        //        return false;
        //    }
        //}

        //private bool addQCSDetail(Model.detail detail, string contr, string errMsg)
        //{
        //    try
        //    {
        //        List<CommandInfo> cmdlist = new List<CommandInfo>();

        //        #region 组织QCS_Detail
        //        StringBuilder sqlDetail = new StringBuilder();
        //        sqlDetail.Append("insert into [QCS_Detail] (");
        //        sqlDetail.Append("order_id,serial,created_at,updated_at,order_creator_name,signing_customer_id,signing_customer_serial,signing_customer_name,cdepname,real_order_serial,contract_serial,final_customer_id,final_customer_serial,final_customer_name,contract_type,amount,sales_department_name,project_name,sales_name,customer_type,pre_sales_name,project_manager,pre_stock,pre_delivery,final_customer_industry,pre_assemble,approach_date_request,data_migration,tuning_service,hardware_compatibility,training_description,arrival_date_request,cargo_ready_date,actual_delivery_date,hardware_purchase,software_purchase,service,implement_service,after_sales_service,bonus,biding_document,biding_service,third_party_training,resident_service,capital_cost,transport_insurance,poc,tax,total_cost,gross_profit,pretax_margin,after_tax_margin,hardware_margin,floor_level)");
        //        sqlDetail.Append(" values (");
        //        sqlDetail.Append("@order_id,@serial,@created_at,@updated_at,@order_creator_name,@signing_customer_id,@signing_customer_serial,@signing_customer_name,@cdepname,@real_order_serial,@contract_serial,@final_customer_id,@final_customer_serial,@final_customer_name,@contract_type,@amount,@sales_department_name,@project_name,@sales_name,@customer_type,@pre_sales_name,@project_manager,@pre_stock,@pre_delivery,@final_customer_industry,@pre_assemble,@approach_date_request,@data_migration,@tuning_service,@hardware_compatibility,@training_description,@arrival_date_request,@cargo_ready_date,@actual_delivery_date,@hardware_purchase,@software_purchase,@service,@implement_service,@after_sales_service,@bonus,@biding_document,@biding_service,@third_party_training,@resident_service,@capital_cost,@transport_insurance,@poc,@tax,@total_cost,@gross_profit,@pretax_margin,@after_tax_margin,@hardware_margin,@floor_level)");
        //        SqlParameter[] parameters = {
        //            new SqlParameter("@order_id", SqlDbType.Int,4),
        //            new SqlParameter("@serial", SqlDbType.NVarChar,100),
        //            new SqlParameter("@created_at", SqlDbType.NVarChar,100),
        //            new SqlParameter("@updated_at", SqlDbType.NVarChar,100),
        //            new SqlParameter("@order_creator_name", SqlDbType.NVarChar,100),
        //            new SqlParameter("@signing_customer_id", SqlDbType.Int,4),
        //            new SqlParameter("@signing_customer_serial", SqlDbType.NVarChar,100),
        //            new SqlParameter("@signing_customer_name", SqlDbType.NVarChar,100),
        //            new SqlParameter("@cdepname", SqlDbType.NVarChar,100),
        //            new SqlParameter("@real_order_serial", SqlDbType.NVarChar,100),
        //            new SqlParameter("@contract_serial", SqlDbType.NVarChar,100),
        //            new SqlParameter("@final_customer_id", SqlDbType.Int,4),
        //            new SqlParameter("@final_customer_serial", SqlDbType.NVarChar,100),
        //            new SqlParameter("@final_customer_name", SqlDbType.NVarChar,100),
        //            new SqlParameter("@contract_type", SqlDbType.NVarChar,100),
        //            new SqlParameter("@amount", SqlDbType.Decimal,9),
        //            new SqlParameter("@sales_department_name", SqlDbType.NVarChar,100),
        //            new SqlParameter("@project_name", SqlDbType.NVarChar,100),
        //            new SqlParameter("@sales_name", SqlDbType.NVarChar,100),
        //            new SqlParameter("@customer_type", SqlDbType.NVarChar,100),
        //            new SqlParameter("@pre_sales_name", SqlDbType.NVarChar,100),
        //            new SqlParameter("@project_manager", SqlDbType.NVarChar,100),
        //            new SqlParameter("@pre_stock", SqlDbType.Int,4),
        //            new SqlParameter("@pre_delivery", SqlDbType.Int,4),
        //            new SqlParameter("@final_customer_industry", SqlDbType.NVarChar,100),
        //            new SqlParameter("@pre_assemble", SqlDbType.Int,4),
        //            new SqlParameter("@approach_date_request", SqlDbType.NVarChar,100),
        //            new SqlParameter("@data_migration", SqlDbType.Int,4),
        //            new SqlParameter("@tuning_service", SqlDbType.NVarChar,100),
        //            new SqlParameter("@hardware_compatibility", SqlDbType.Int,4),
        //            new SqlParameter("@training_description", SqlDbType.NVarChar,100),
        //            new SqlParameter("@arrival_date_request", SqlDbType.NVarChar,100),
        //            new SqlParameter("@cargo_ready_date", SqlDbType.NVarChar,100),
        //            new SqlParameter("@actual_delivery_date", SqlDbType.NVarChar,100),
        //            new SqlParameter("@hardware_purchase", SqlDbType.Decimal,9),
        //            new SqlParameter("@software_purchase", SqlDbType.Decimal,9),
        //            new SqlParameter("@service", SqlDbType.Decimal,9),
        //            new SqlParameter("@implement_service", SqlDbType.Decimal,9),
        //            new SqlParameter("@after_sales_service", SqlDbType.Decimal,9),
        //            new SqlParameter("@bonus", SqlDbType.Decimal,9),
        //            new SqlParameter("@biding_document", SqlDbType.Decimal,9),
        //            new SqlParameter("@biding_service", SqlDbType.Decimal,9),
        //            new SqlParameter("@third_party_training", SqlDbType.Decimal,9),
        //            new SqlParameter("@resident_service", SqlDbType.Decimal,9),
        //            new SqlParameter("@capital_cost", SqlDbType.Decimal,9),
        //            new SqlParameter("@transport_insurance", SqlDbType.Decimal,9),
        //            new SqlParameter("@poc", SqlDbType.Decimal,9),
        //            new SqlParameter("@tax", SqlDbType.Decimal,9),
        //            new SqlParameter("@total_cost", SqlDbType.Decimal,9),
        //            new SqlParameter("@gross_profit", SqlDbType.Decimal,9),
        //            new SqlParameter("@pretax_margin", SqlDbType.Decimal,9),
        //            new SqlParameter("@after_tax_margin", SqlDbType.Decimal,9),
        //            new SqlParameter("@hardware_margin", SqlDbType.Decimal,9),
        //            new SqlParameter("@floor_level", SqlDbType.Decimal,9)};
        //        parameters[0].Value = detail.order_id == ""  0 : Convert.ToInt32(detail.order_id);
        //        parameters[1].Value = detail.serial;
        //        parameters[2].Value = detail.created_at;
        //        parameters[3].Value = detail.updated_at;
        //        parameters[4].Value = detail.order_creator_name;
        //        parameters[5].Value = detail.signing_customer_id == ""  0 : Convert.ToInt32(detail.signing_customer_id);
        //        parameters[6].Value = detail.signing_customer_serial;
        //        parameters[7].Value = detail.signing_customer_name;
        //        parameters[8].Value = detail.cdepname;
        //        parameters[9].Value = detail.real_order_serial;
        //        parameters[10].Value = detail.contract_serial;
        //        parameters[11].Value = detail.final_customer_id == ""  0 : Convert.ToInt32(detail.final_customer_id);
        //        parameters[12].Value = detail.final_customer_serial;
        //        parameters[13].Value = detail.final_customer_name;
        //        parameters[14].Value = detail.contract_type;
        //        parameters[15].Value = detail.amount == ""  0 : Convert.ToDecimal(detail.amount);
        //        parameters[16].Value = detail.sales_department_name;
        //        parameters[17].Value = detail.project_name;
        //        parameters[18].Value = detail.sales_name;
        //        parameters[19].Value = detail.customer_type;
        //        parameters[20].Value = detail.pre_sales_name;
        //        parameters[21].Value = detail.project_manager;
        //        parameters[22].Value = detail.pre_stock == ""  0 : Convert.ToInt32(detail.pre_stock);
        //        parameters[23].Value = detail.pre_delivery == ""  0 : Convert.ToInt32(detail.pre_delivery);
        //        parameters[24].Value = detail.final_customer_industry;
        //        parameters[25].Value = detail.pre_assemble == ""  0 : Convert.ToInt32(detail.pre_assemble);
        //        parameters[26].Value = detail.approach_date_request;
        //        parameters[27].Value = detail.data_migration == ""  0 : Convert.ToInt32(detail.data_migration);
        //        parameters[28].Value = detail.tuning_service;
        //        parameters[29].Value = detail.hardware_compatibility == ""  0 : Convert.ToInt32(detail.hardware_compatibility);
        //        parameters[30].Value = detail.training_description;
        //        parameters[31].Value = detail.arrival_date_request;
        //        parameters[32].Value = detail.cargo_ready_date;
        //        parameters[33].Value = detail.actual_delivery_date;
        //        parameters[34].Value = detail.hardware_purchase == ""  0 : Convert.ToDecimal(detail.hardware_purchase);
        //        parameters[35].Value = detail.software_purchase == ""  0 : Convert.ToDecimal(detail.software_purchase);
        //        parameters[36].Value = detail.service == ""  0 : Convert.ToDecimal(detail.service);
        //        parameters[37].Value = detail.implement_service == ""  0 : Convert.ToDecimal(detail.implement_service);
        //        parameters[38].Value = detail.after_sales_service == ""  0 : Convert.ToDecimal(detail.after_sales_service);
        //        parameters[39].Value = detail.bonus == ""  0 : Convert.ToDecimal(detail.bonus);
        //        parameters[40].Value = detail.biding_document == ""  0 : Convert.ToDecimal(detail.biding_document);
        //        parameters[41].Value = detail.biding_service == ""  0 : Convert.ToDecimal(detail.biding_service);
        //        parameters[42].Value = detail.third_party_training == ""  0 : Convert.ToDecimal(detail.third_party_training);
        //        parameters[43].Value = detail.resident_service == ""  0 : Convert.ToDecimal(detail.resident_service);
        //        parameters[44].Value = detail.capital_cost == ""  0 : Convert.ToDecimal(detail.capital_cost);
        //        parameters[45].Value = detail.transport_insurance == ""  0 : Convert.ToDecimal(detail.transport_insurance);
        //        parameters[46].Value = detail.poc == ""  0 : Convert.ToDecimal(detail.poc);
        //        parameters[47].Value = detail.tax == ""  0 : Convert.ToDecimal(detail.tax);
        //        parameters[48].Value = detail.total_cost == ""  0 : Convert.ToDecimal(detail.total_cost);
        //        parameters[49].Value = detail.gross_profit == ""  0 : Convert.ToDecimal(detail.gross_profit);
        //        parameters[50].Value = detail.pretax_margin == ""  0 : Convert.ToDecimal(detail.pretax_margin);
        //        parameters[51].Value = detail.after_tax_margin == ""  0 : Convert.ToDecimal(detail.after_tax_margin);
        //        parameters[52].Value = detail.hardware_margin == ""  0 : Convert.ToDecimal(detail.hardware_margin);
        //        parameters[53].Value = detail.floor_level == ""  0 : Convert.ToDecimal(detail.floor_level);
        //        CommandInfo cmd = new CommandInfo(sqlDetail.ToString(), parameters);
        //        cmdlist.Add(cmd);
        //        #endregion

        //        foreach (Payment_termsItem payment in detail.payment_terms)
        //        {
        //            #region 组织QCS_Payment
        //            StringBuilder sqlPayment = new StringBuilder();
        //            sqlPayment.Append("insert into [QCS_Payment] (");
        //            sqlPayment.Append("detail_serial,term_description,planned_payment_date,payment_amount,payment_ratio)");
        //            sqlPayment.Append(" values (");
        //            sqlPayment.Append("@detail_serial,@term_description,@planned_payment_date,@payment_amount,@payment_ratio)");
        //            SqlParameter[] parameters2 = {
        //            new SqlParameter("@detail_serial", SqlDbType.NVarChar,100),
        //            new SqlParameter("@term_description", SqlDbType.NVarChar,100),
        //            new SqlParameter("@planned_payment_date", SqlDbType.NVarChar,100),
        //            new SqlParameter("@payment_amount", SqlDbType.Decimal,9),
        //            new SqlParameter("@payment_ratio", SqlDbType.Decimal,9)};
        //            parameters2[0].Value = detail.serial;
        //            parameters2[1].Value = payment.term_description;
        //            parameters2[2].Value = payment.planned_payment_date;
        //            parameters2[3].Value = payment.payment_amount == ""  0 : Convert.ToDecimal(payment.payment_amount);
        //            parameters2[4].Value = payment.payment_ratio == ""  0 : Convert.ToDecimal(payment.payment_ratio);
        //            CommandInfo cmd2 = new CommandInfo(sqlPayment.ToString(), parameters2);
        //            cmdlist.Add(cmd2);
        //            #endregion
        //        }

        //        foreach (Acceptance_checkItem acceptance in detail.acceptance_check)
        //        {
        //            #region 组织QCS_Acceptance
        //            StringBuilder sqlAcceptance = new StringBuilder();
        //            sqlAcceptance.Append("insert into [QCS_Acceptance] (");
        //            sqlAcceptance.Append("detail_serial,check_point,estimated_check_date,actual_check_date,financial_actual_acceptance_time)");
        //            sqlAcceptance.Append(" values (");
        //            sqlAcceptance.Append("@detail_serial,@check_point,@estimated_check_date,@actual_check_date,@financial_actual_acceptance_time)");
        //            SqlParameter[] parameters3 = {
        //            new SqlParameter("@detail_serial", SqlDbType.NVarChar,100),
        //            new SqlParameter("@check_point", SqlDbType.NVarChar,100),
        //            new SqlParameter("@estimated_check_date", SqlDbType.NVarChar,100),
        //            new SqlParameter("@actual_check_date", SqlDbType.NVarChar,100),
        //            new SqlParameter("@financial_actual_acceptance_time", SqlDbType.NVarChar,100)};
        //            parameters3[0].Value = detail.serial;
        //            parameters3[1].Value = acceptance.check_point;
        //            parameters3[2].Value = acceptance.estimated_check_date;
        //            parameters3[3].Value = acceptance.actual_check_date;
        //            parameters3[4].Value = acceptance.financial_actual_acceptance_time;
        //            CommandInfo cmd3 = new CommandInfo(sqlAcceptance.ToString(), parameters3);
        //            cmdlist.Add(cmd3);
        //            #endregion
        //        }

        //        foreach (MaterialItem material in detail.material)
        //        {
        //            #region 组织QCS_Material
        //            StringBuilder sqlMaterial = new StringBuilder();
        //            sqlMaterial.Append("insert into [QCS_Material] (");
        //            sqlMaterial.Append("id,detail_serial,serial,type_name,quantity,is_giveaway,unit_price_including_tax,unit_price_excluding_tax,price_excluding_tax,price_including_tax,tax,out_tax_rate)");
        //            sqlMaterial.Append(" values (");
        //            sqlMaterial.Append("@id,@detail_serial,@serial,@type_name,@quantity,@is_giveaway,@unit_price_including_tax,@unit_price_excluding_tax,@price_excluding_tax,@price_including_tax,@tax,@out_tax_rate)");
        //            SqlParameter[] parameters4 = {
        //            new SqlParameter("@id", SqlDbType.Int,4),
        //            new SqlParameter("@detail_serial", SqlDbType.NVarChar,100),
        //            new SqlParameter("@serial", SqlDbType.NVarChar,100),
        //            new SqlParameter("@type_name", SqlDbType.NVarChar,100),
        //            new SqlParameter("@quantity", SqlDbType.Int,4),
        //            new SqlParameter("@is_giveaway", SqlDbType.Int,4),
        //            new SqlParameter("@unit_price_including_tax", SqlDbType.Decimal,9),
        //            new SqlParameter("@unit_price_excluding_tax", SqlDbType.Decimal,9),
        //            new SqlParameter("@price_excluding_tax", SqlDbType.Decimal,9),
        //            new SqlParameter("@price_including_tax", SqlDbType.Decimal,9),
        //            new SqlParameter("@tax", SqlDbType.Decimal,9),
        //            new SqlParameter("@out_tax_rate", SqlDbType.Decimal,9)};
        //            parameters4[0].Value = material.id == ""  0 : Convert.ToInt32(material.id);
        //            parameters4[1].Value = detail.serial;
        //            parameters4[2].Value = material.serial;
        //            parameters4[3].Value = material.type_name;
        //            parameters4[4].Value = material.quantity == ""  0 : Convert.ToInt32(material.quantity);
        //            parameters4[5].Value = material.is_giveaway == ""  0 : Convert.ToInt32(material.is_giveaway);
        //            parameters4[6].Value = material.unit_price_including_tax == ""  0 : Convert.ToDecimal(material.unit_price_including_tax);
        //            parameters4[7].Value = material.unit_price_excluding_tax == ""  0 : Convert.ToDecimal(material.unit_price_excluding_tax);
        //            parameters4[8].Value = material.price_excluding_tax == ""  0 : Convert.ToDecimal(material.price_excluding_tax);
        //            parameters4[9].Value = material.price_including_tax == ""  0 : Convert.ToDecimal(material.price_including_tax);
        //            parameters4[10].Value = material.tax == ""  0 : Convert.ToDecimal(material.tax);
        //            parameters4[11].Value = material.out_tax_rate == ""  0 : Convert.ToDecimal(material.out_tax_rate);
        //            CommandInfo cmd4 = new CommandInfo(sqlMaterial.ToString(), parameters4);
        //            cmdlist.Add(cmd4);

        //            foreach (ItemsItem item in material.items)
        //            {
        //                #region 组织QCS_MaterialItem
        //                StringBuilder sqlMaterialItem = new StringBuilder();
        //                sqlMaterialItem.Append("insert into [QCS_MaterialItem] (");
        //                sqlMaterialItem.Append("detail_serial,material_serial,id,serial,material_name,quantity,remark,unit,warranty_period,component_name,item_name,unit_price,total_price,out_tax_rate)");
        //                sqlMaterialItem.Append(" values (");
        //                sqlMaterialItem.Append("@detail_serial,@material_serial,@id,@serial,@material_name,@quantity,@remark,@unit,@warranty_period,@component_name,@item_name,@unit_price,@total_price,@out_tax_rate)");
        //                SqlParameter[] parameters5 = {
        //                new SqlParameter("@detail_serial", SqlDbType.NVarChar,100),
        //                new SqlParameter("@material_serial", SqlDbType.NVarChar,100),
        //                new SqlParameter("@id", SqlDbType.Int,4),
        //                new SqlParameter("@serial", SqlDbType.NVarChar,100),
        //                new SqlParameter("@material_name", SqlDbType.NVarChar,1000),
        //                new SqlParameter("@quantity", SqlDbType.Int,4),
        //                new SqlParameter("@remark", SqlDbType.NVarChar,500),
        //                new SqlParameter("@unit", SqlDbType.NVarChar,100),
        //                new SqlParameter("@warranty_period", SqlDbType.Int,4),
        //                new SqlParameter("@component_name", SqlDbType.NVarChar,100),
        //                new SqlParameter("@item_name", SqlDbType.NVarChar,100),
        //                new SqlParameter("@unit_price", SqlDbType.Decimal,9),
        //                new SqlParameter("@total_price", SqlDbType.Decimal,9),
        //                new SqlParameter("@out_tax_rate", SqlDbType.Decimal,9)};
        //                parameters5[0].Value = detail.serial;
        //                parameters5[1].Value = material.serial;
        //                parameters5[2].Value = item.id == ""  0 : Convert.ToInt32(item.id);
        //                parameters5[3].Value = item.serial;
        //                parameters5[4].Value = item.material_name;
        //                parameters5[5].Value = item.quantity == ""  0 : Convert.ToInt32(item.quantity);
        //                parameters5[6].Value = item.remark;
        //                parameters5[7].Value = item.unit;
        //                parameters5[8].Value = item.warranty_period == ""  0 : Convert.ToInt32(item.warranty_period);
        //                parameters5[9].Value = item.component_name;
        //                parameters5[10].Value = item.item_name;
        //                parameters5[11].Value = item.unit_price == ""  0 : Convert.ToDecimal(item.warranty_period);
        //                parameters5[12].Value = item.total_price == ""  0 : Convert.ToDecimal(item.warranty_period);
        //                parameters5[13].Value = item.out_tax_rate == ""  0 : Convert.ToDecimal(item.warranty_period);
        //                CommandInfo cmd5 = new CommandInfo(sqlMaterialItem.ToString(), parameters5);
        //                cmdlist.Add(cmd5);
        //                #endregion
        //            }
        //            #endregion
        //        }

        //        if (cmdlist.Count > 0)
        //        {
        //            DbHelperSQL.ExecuteSqlTran(cmdlist, contr);
        //        }
        //        return true;
        //    }
        //    catch (Exception ex)
        //    {
        //        errMsg = ex.ToString();
        //        return false;
        //    }
        //}


        //private UFIDA.U8.DB.CommandInfo GetCustomerUpdCommand(Model.customer model, string connstr)
        //{
        //    List<UFIDA.U8.DB.CommandInfo> sqllist = new List<UFIDA.U8.DB.CommandInfo>();
        //    UFIDA.U8.DB.Model.Customer cus = UFIDA.U8.DB.DAL.Customer.GetModel(model.serial, connstr);
        //    if (cus == null)
        //    {
        //        return null;
        //    }
        //    cus.cCusName = model.name;
        //    cus.cCusAbbName = model.name;
        //    cus.cCusAddress = model.address;
        //    cus.dCusCreateDatetime = Convert.ToDateTime(model.created_at);
        //    cus.cCusDefine1 = model.id.ToString();
        //    cus.cCusDefine2 = model.region;
        //    cus.cCusDefine3 = model.province;
        //    cus.cCusDefine4 = model.city;
        //    cus.cCusDefine5 = model.sales == null  "" : model.sales.name;
        //    cus.cCusDefine6 = model.industry;
        //    cus.cCusMngTypeCode = "999";
        //    cus.cCusExch_name = "人民币";
        //    return UFIDA.U8.DB.DAL.Customer.GetUpdCommandWQ(cus);
        //}

        //private UFIDA.U8.DB.CommandInfo GetCustomerAddCommand(Model.customer model, string connstr)
        //{
        //    UFIDA.U8.DB.Model.Customer cus = new DB.Model.Customer();
        //    cus.cCusCode = model.serial;
        //    cus.cCusName = model.name;
        //    cus.cCusAbbName = model.name;
        //    cus.cCCCode = "09";
        //    cus.cCusAddress = model.address;
        //    cus.cCusDefine1 = model.id.ToString();
        //    cus.dCusDevDate = DateTime.Now;
        //    cus.cCusMngTypeCode = "999";
        //    cus.cCusExch_name = "人民币";

        //    cus.cCusDefine1 = model.id.ToString();

        //    cus.cCusDefine2 = model.region;
        //    cus.cCusDefine3 = model.province;
        //    cus.cCusDefine4 = model.city;
        //    cus.cCusDefine5 = model.sales == null  "" : model.sales.name;
        //    cus.cCusDefine6 = model.industry;
        //    return UFIDA.U8.DB.DAL.Customer.GetAddCommand(cus);
        //}


        //private void buttonX7_Click(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        dsdetail = this.queryData4();
        //        bdsdetail.DataSource = dsdetail;
        //        bdsdetail.DataMember = "Table1";
        //        dcount.Text = bdsdetail.Count.ToString();
        //    }
        //    catch (Exception ex)
        //    {
        //        U8.PUB.LogHelper.WriteLine(this.GetType() + ":" + ex.Message);
        //        MessageBox.Show(ex.Message);
        //    }
        //}



        //private void buttonX8_Click(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        dsWB = this.queryData5();
        //        bdsWB.DataSource = dsWB;
        //        bdsWB.DataMember = "Table1";
        //        wcount.Text = bdsWB.Count.ToString();
        //    }
        //    catch (Exception ex)
        //    {
        //        U8.PUB.LogHelper.WriteLine(this.GetType() + ":" + ex.Message);
        //        MessageBox.Show(ex.Message);
        //    }
        //}

        ////查询QCS维保数据——2021.10.28(liny)
        //private DataSet queryData5()
        //{
        //    //获取url
        //    string url = System.Web.Configuration.WebConfigurationManager.AppSettings["qcsurl"]; // "https://qcs1.woqutech.com:4665/";

        //    //读取页面输入的参数
        //    string order_serial = textBoxX7.Text;//订单号
        //    string contract_serial = textBoxX6.Text;//合同号

        //    try
        //    {
        //        //调用QCS·token接口获取token
        //        token = Common.getQCSTkoen(url);
        //        if (token == null)
        //        {
        //            MessageBox.Show("获取Token失败");
        //            return null;
        //        }

        //        //根据查询条件获取订单信息
        //        DataTable dt = new DataTable();
        //        wbs = Common.GetQCSWB(url, order_serial, contract_serial, token, ref dt);
        //        if (wbs == null)
        //        {
        //            MessageBox.Show("获取Qcs订单失败");
        //            return null;
        //        }
        //        DataSet ds = new DataSet();
        //        ds.Tables.Add(dt);
        //        return ds;

        //    }
        //    catch (Exception e)
        //    {
        //        U8.PUB.LogHelper.WriteLine("queryData:" + e.Message);
        //        throw e;
        //    }
        //}
        #endregion

    }
}
